Im facing the error when execute the data reader command in vb.net. it throw handling. This field like when you enter employee id in textbox then it will capture in database for other field name,department.
here is my code
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String =ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Dim sqlQuery As String = "SELECT * hr_record WHERE Emplid='" & txt1.Text & "'"
Using sqlConn As New MySqlConnection(strConnectionString)
Using sqlComm As New MySqlCommand()
With sqlComm
.CommandText = sqlQuery
End With
Try
sqlConn.Open()
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
txt1.Text = sqlReader("Emplid").ToString()
TextBox1.Text = sqlReader("Nama").ToString()
TextBox2.Text = sqlReader("DeptDesc").ToString()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
Try to change your select query like
Dim sqlQuery As String = "SELECT * from hr_record WHERE Emplid='" & txt1.Text & "'"
Note:- Cannot use code like that in Page_Load.Try to make one Function and call that function from Page_Load and always use Parameterized query.
Updated answer:
Page_Load
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
DataBind()
End Sub
Outside Method:
Public Sub DataBind()
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Using Con As New MySqlConnection(sConnection)
Con.Open()
Using Com As New MySqlCommand("SELECT * from hr_record WHERE Emplid='"txt1.Text
"'", Con)
Using RDR = Com.ExecuteReader()
If RDR.HasRows Then
Do While RDR.Read
txt1.Text = RDR.Item("Emplid").ToString()
TextBox1.Text = RDR.Item("Nama").ToString()
TextBox2.Text = RDR.Item("DeptDesc").ToString()
Loop
End If
End Using
End Using
Con.Close()
End Using
End Sub
Note:Try to implement your logic like that and also modified as per your requirements.
Hope it works.
You try to get Emplid in page load,but it's still nothing you should use button to check if Emplid exist
Thanks to all thanks helping me..finally this code it works thanks to all .
this the code will be function
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String = ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Using sqlConn As New MySqlConnection(strConnectionString)
sqlConn.Open()
Using sqlComm As New MySqlCommand()
sqlComm.Connection = sqlConn
With sqlComm
.CommandText = "SELECT * from hr_record WHERE Emplid='" & txt1.Text & "'"
End With
Try
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
txt1.Text = sqlReader("Emplid").ToString()
TextBox1.Text = sqlReader("Nama").ToString()
txtdep.Text = sqlReader("DeptDesc").ToString()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
sqlConn.Close()
End Using
End Using
End Sub
Related
I would like to search data in a textbox . Below is my code. I tried to search but nothing happen.
If Not Me.IsPostBack Then
Me.SearchPanelId()
End If
End Sub
Private Sub SearchPanelId()
Dim ConnectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using con As New SqlConnection(ConnectionString)
Using cmd As New SqlCommand()
Dim sql As String = "SELECT panelid, panelname, paneltype FROM PANEL_TABLE"
If Not String.IsNullOrEmpty(TextBox1.Text.Trim()) Then
sql += " WHERE panelid LIKE #panelid + '%'"
cmd.Parameters.AddWithValue("#panelid", TextBox1.Text.Trim())
End If
cmd.CommandText = sql
cmd.Connection = con
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Sub
Protected Sub Search(sender As Object, e As EventArgs)
Me.SearchPanelId()
End Sub
Protected Sub OnPaging(sender As Object, e As GridViewPageEventArgs)
GridView1.PageIndex = e.NewPageIndex
Me.SearchPanelId()
End Sub
Do the validation before you start creating objects. You need to check if that datatype of the ID is valid. I guessed that this was an Integer type but check your database. If I am wrong and the datatype is .VarChar then see the second rendition. :-) The Like keyword does not make any sense with a numeric field.
Don't use .AddWithValue See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
A DataAdapter is not necessary. Just use the load method of the DataTable.
Private Sub SearchPanelId()
Dim IDValue As Integer
Dim dt As New DataTable
If String.IsNullOrEmpty(TextBox1.Text.Trim()) OrElse Not Integer.TryParse(TextBox1.Text.Trim, IDValue) Then
Return
End If
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT panelid, panelname, paneltype FROM PANEL_TABLE WHERE panelid = #panelid", con)
cmd.Parameters.Add("#panelid", SqlDbType.Int).Value = IDValue
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
If Id is a .VarChar
Private Sub SearchPanelId()
Dim dt As New DataTable
If String.IsNullOrEmpty(TextBox1.Text.Trim()) Then
Return
End If
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT panelid, panelname, paneltype FROM PANEL_TABLE WHERE panelid Like #panelid", con)
cmd.Parameters.Add("#panelid", SqlDbType.VarChar).Value = TextBox1.Text.Trim() & "%"
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
I'm facing very un natural problem suddenly. I have DropDownList with autopostback is true. Postback executes a method which populates other things onpage according to selection. Now When I select any value first time from that dropdown then page gets postback but nothing get populate but from second time it works fine. Even I put breakpoint on that dropdown & it's not even hitting breakpoint for first postback.
<asp:DropDownList ID="ClientCode" runat="server" ClientIDMode="Static" CssClass="field-pitch" AutoPostBack="true"></asp:DropDownList>
Private Sub ClientCode_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ClientCode.SelectedIndexChanged
Me.populateConsignerDetails()
End Sub
Private Sub populateConsignerDetails()
Try
Dim str As String = "SELECT * FROM clientsDetails WHERE clientID = #clientID"
con.Open()
Dim cmd As New MySqlCommand(str, con)
cmd.Parameters.AddWithValue("#clientID", ClientCode.SelectedItem.ToString)
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
con.Close()
Dim payingParty As String = String.Empty
If dt.Rows.Count > 0 Then
consignerName.Text = dt.Rows(0)("clientName").ToString
consignerAddress.Text = dt.Rows(0)("companyAddress").ToString
consignerMobile1.Text = dt.Rows(0)("contactNumber1").ToString
consignerCity.Text = dt.Rows(0)("city").ToString
consignerState.Text = dt.Rows(0)("state").ToString
consignerPinCode.Text = dt.Rows(0)("pinCode").ToString
End If
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Update
Private Sub myadmin_shipment_details2_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
populateClient()
End If
End Sub
Private Sub populateClient()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select * from clientsDetails where status = 'active'"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("clientID").ToString()
item.Value = sdr("ClientName").ToString()
ClientCode.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub
I'm a beginner in vb.net. Currently I'm develop a simple application by using a grid view. however, I'm facing a problem in deleting the data. When I click delete button, it keep adding the blank line. and this blank line is affected my database also. and this blank line also can't be deleted from database manually.
here my code behind
`Imports System.Data.SqlClient
Imports System.Drawing
Imports System.Data
Imports System.Configuration
Imports System.Linq
Partial Class test2
Inherits System.Web.UI.Page
Dim AMS As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("AMS").ConnectionString
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindData()
End If
End Sub
Private Sub BindData()
Dim dt As DataTable = New DataTable
Dim strConnString As String = ConfigurationManager.ConnectionStrings("AMS").ConnectionString
Using con As SqlConnection = New SqlConnection(strConnString)
Dim strQuery As String = "SELECT * FROM ModuleDetail"
Using cmd As SqlCommand = New SqlCommand(strQuery)
Dim sda As SqlDataAdapter = New SqlDataAdapter
cmd.Connection = con
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Sub
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
Dim IsDeleted As Boolean = False
Dim ModuleID As String = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Value.ToString())
Dim ModuleName As Label = CType(GridView1.Rows(e.RowIndex).FindControl("lblModuleName"), Label)
Dim SubModule As Label = CType(GridView1.Rows(e.RowIndex).FindControl("lblSubModule"), Label)
Dim strConnString As String = ConfigurationManager.ConnectionStrings("AMS").ConnectionString
Using con As SqlConnection = New SqlConnection(strConnString)
Using cmd As SqlCommand = New SqlCommand
cmd.CommandType = CommandType.Text
cmd.CommandText = "DELETE FROM ModuleDetail WHERE ModuleID=#ModuleID"
cmd.Parameters.AddWithValue("#ModuleID", ModuleID)
cmd.Connection = con
con.Open()
IsDeleted = cmd.ExecuteNonQuery() > 0
con.Close()
GridView1.DataSource = cmd
GridView1.DataBind()
End Using
End Using
If IsDeleted Then
lblMsg.Text = "'" & SubModule.Text & "' details has been deleted successfully!"
lblMsg.ForeColor = System.Drawing.Color.Green
BindData()
Else
lblMsg.Text = "Error while deleting '" & SubModule.Text & "' details"
lblMsg.ForeColor = System.Drawing.Color.Red
End If
End Sub
`
I have try a few code from others sources but it shows the same logic error which keep adding the blank line. I hope you guys can help me to solve the issue.
Though it might not relevant to your problem context, but I have observed a couple of issues from your code:
1) It seems you are binding grid twice after row delete.
2) Try commenting following lines since you already calling BindData() whithin IsDeleted flag check.
GridView1.DataSource = cmd;
GridView1.DataBind();
3) You are assigning the 'Command' object: cmd to the Grid's datasource which is not correct. Check your BindData(...) method how you need to bind Grid actually.
I'm attempting to create a search page, which will display the results into a Gridview, but keep getting the following error when I click the my search button: Invalid attempt to call Read when reader is closed.
This is my code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim connectionString As [String] = ConfigurationManager.ConnectionStrings("myDbConnectionString1").ConnectionString
Dim connection As New SqlConnection(connectionString)
connection.Open()
Dim mySQLQuery As String
Dim vID As String
vID = Request.QueryString("pgResults")
mySQLQuery = "SELECT name,address,results,url FROM myTb WHERE name LIKE '%" + TextBox1.Text + "%'"
Dim myCommand As New SqlCommand(mySQLQuery, connection)
Dim myReader1 As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
While (myReader1.Read())
GridView1.DataSource = myReader1
GridView1.DataBind()
End While
panelBody.Visible = False
panelSearchResults.Visible = True
connection.Close()
End Sub
Could I get some help please?
You cannot call Read() and then use a IDataReader as a DataSource, let DataBinding handle that. try this:
Dim myReader1 As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
GridView1.DataSource = myReader1
GridView1.DataBind()
Protected Sub GridView3_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView3.RowCommand
For Each myRow As GridViewRow In GridView3.Rows
'Find the checkbox
Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
If e.CommandName = "Sumit" Then
Dim cmd As New Data.SqlClient.SqlCommand
Dim con As New Data.SqlClient.SqlConnection(constr)
Try
Dim strSql As String = "DELETE * FROM hotels WHERE hotelid =" & lab1.Text
'------------"
con.Open()
cmd.Connection = con
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cmd.Dispose()
con.Dispose()
End Try
End If
Next
GridView3.DataBind()
End Sub
I'm not sure why you think that will delete everything in the table, as I'm fairly certain it will not even execute. DELETE does not require any columns or * to be specified. It should just be DELETE FROM hotels WHERE [etc, etc].
Also, you should seriously consider giving this article a read: How To: Protect From SQL Injection in ASP.NET. Especially "Step 3. Use Parameters with Dynamic SQL", which detail how you could change your code to prevent SQL injection.
I believe what you are looking for is this:
Protected Sub GridView3_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView3.RowCommand
Dim myRow As GridViewRow = DirectCast((System.Web.UI.Control)(sender)).NamingContainer, GridViewRow)
'Find the checkbox
Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
If e.CommandName = "Sumit" Then
Dim cmd As New Data.SqlClient.SqlCommand
Dim con As New Data.SqlClient.SqlConnection(constr)
Try
Dim strSql As String = "DELETE FROM hotels WHERE hotelid =" & lab1.Text
'------------"
con.Open()
cmd.Connection = con
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cmd.Dispose()
con.Dispose()
End Try
End If
GridView3.DataBind()
End Sub
The syntax may be off I'm not too familiar with VB. As well it would be better to pass the ID of the hotel record in the e.CommandArgument thus you would not have to retrieve it from a label on the page. It is deleting all your records because you are looping through all your rows in the grid view and deleting each record.