Read a record in SQL and .NET
-
I can fill a datagrid from SQL.. I can do this with ADO/JET but I am at a loss on how to get a single record to display on my form from an SQL database using my current connection. I am looking for a clear and simple example. Thanks Gollnick
There should be lots of examples out there of how to return multiple records, looping through records, returning one record etc. But here's a simple example of how I get back a record from a SELECT statement:
Private Function GetCustName(ByVal CustNum As String) As String Dim strConn As String = ConfigurationSettings.AppSettings.Item("connectionstring") 'Read connection string from web.config Dim conSQL As New SqlConnection(strConn) 'Create the connection Dim cmdSQL As New SqlCommand("SELECT CustName FROM Customers WHERE CustNum ='" & CustNum & "'", conSQL) 'The query I want to run Dim Rdr As SqlDataReader conSQL.Open() 'Open the connection Rdr = cmdSQL.ExecuteReader() 'Execute the query Rdr.Read() 'Read the record (only returns ONE record!) GetCustName = IIf(IsDBNull(Rdr("CustName")), "", Rdr("CustName")) 'Read the value from a field called 'CustName' conSQL.Close() End Function
This function returns a value from a record when you pass it a search criteris. If you want to populate text boxes on your form, then after the 'Rdr.Read()' line, you could do something like:myName.text = Rdr("Name") myAddress1.text = Rdr("Address1") myAddress2.text = Rdr("Address2") etc...
Hope this helps, Regards, John. www.silveronion.com[^]