preethamonline
asked on
Using list box to fetch data from database
Hello Guys, I am stuck in a situation where after the data is entered in the database, the emp id and emp name appear in the listbox. (See pic. attached). When i click on the empid in the list box , i want to load the values to the respective controls to enable the user to edit them if needed. Also not quite sure if should place this in the selectedindexchanged event or somewhere else. Please guide me as to where i have gone wrong. Attached is the source code that i'm using. Thanks in advance
Protected Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim con As New System.Data.OleDb.OleDbConnection
Dim dreader As System.Data.OleDb.OleDbDataReader
Dim myCommand As New System.Data.OleDb.OleDbCommand
Dim myPath As String
myPath = Server.MapPath("hayat.mdb")
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data source=" & myPath & ";"
Dim emp As String = txtempid.Text
Dim empid As String = emp.Substring(0, emp.IndexOf(" -"))
myCommand.CommandText = "select * from empdetails where empid = " & empid & " order by adate"
myCommand.Connection = con
Try
con.Open()
dreader = myCommand.ExecuteReader
While dreader.Read()
txtempid.Text = dreader(1)
txtempname.Text = dreader(2)
txtempdesignation.Text = dreader(3)
End While
Catch ex As Exception
lblmsg.Text = "There is an error" + ex.ToString
Finally
con.Close()
End Try
End Sub
error.bmp
ASKER
Hi dear. Actually my form is designed this way. I actually wanted the editing to be seperate but my manager wanted it to be this way. Any idea how could I accomplish this with a list box.
There is always a way...let me check and test and I'll try to be back soon with a solution.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks a lot dear. Will try it out in the morning.
ASKER
Thanks for your help dear.
2. There is no need to use the EditTemplate of GridView as you wish to use the form-input section. Use the RowEditing event of the GridView and use the code you have pasted above there to bring the data from the database and display in fields. Make sure to present/unhide a Cancel button when you are in Edit Mode.
3. Confirm that EMPID in your database table is an integer or string because it might have affects when you are executing your query. My recommendation is to use stored procedures with SQL Server Express or Full Version if available.