Last post Apr 10, 2008 02:59 PM by Mikesdotnetting
Apr 10, 2008 06:03 AM|AndreCosta|LINK
I have an acess DB and I would like to retrieve a value from a field to a label.
For e.g I have an ID field and I would like to put it on a label so the user can see it, can you guys help me with the code?
Apr 10, 2008 09:43 AM|mmeisel|LINK
Create this label somewhere on your asp.net page.
<asp:Label ID="Label1" runat="server"></asp:Label>
Now time for the ASP.NET code. You can either put this in the body of the document, or create a function. In this example I'll just create a function.
Public Sub button1_click(byVal Source as Object, ByVal E as EventArgs)
' Create database variables
Dim mySQL as String = "SELECT * FROM table1" 'this is your SQL statement, change as desired
Dim myConn as OleDbConnection = new OleDbConnection ( ... ) ' set up your connection string here
Dim Cmd as New OleDbCommand (MySQL, myConn)
Dim myDataReader as OleDbReader
' Open connection and execute the reader
myDataReader = Cmd.ExecuteReader()
' Read first row of datareader
' Get value of the ID. Usually the ID will be the first field (position 0) but this will depend on how your table is designed
' Set Label1 text = to the ID returned
Label1.Text = myDataReader.GetValue(0).ToString()
' Close connection and datareader
myConn = Nothing
myDataReader = Nothing
Apr 10, 2008 09:45 AM|thirumaran007|LINK
If you want get single value from database (i.e. Id only)
Then you can use
it is better then
Apr 10, 2008 09:55 AM|mmeisel|LINK
"Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored."
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx (examples on this page)
It sounds like ExecuteScalar would work but it has some limitations, you can use it just be sure that the ID you want to display is in the first column of the first row returned. This would probably require a WHERE clause in your SQL statement.
Apr 10, 2008 02:59 PM|Mikesdotnetting|LINK
Samples for Access using parameters: