How to lookup a table?

seahck

Member
Joined
Jul 12, 2004
Messages
6
Programming Experience
Beginner
im a newbie and i have some question.
how to lookup a table from a form. during form_load i want to lookup a field from a table to fill inside 1 of the textbox in the form. anyone know it? thank.........
 

mzim

Well-known member
Joined
Jun 3, 2004
Messages
187
Location
Other side of the rock
Programming Experience
1-3
seahck said:
im a newbie and i have some question.
how to lookup a table from a form. during form_load i want to lookup a field from a table to fill inside 1 of the textbox in the form. anyone know it? thank.........
halu,
why wont you use datagrid instead of textbox?

its better to use datagrid in filling data from table.
 

Paszt

Staff member
Joined
Jun 3, 2004
Messages
1,500
Location
Raleigh, NC - USA
Programming Experience
Beginner
If you only need to obtain one field of data from one record returned from a database, I would suggest doing as you propose and use a textbox.

I would suggest using an OleDbCommand (or SqlCommand depending on the type of database) and its ExecuteScalar scalar command.
 

seahck

Member
Joined
Jul 12, 2004
Messages
6
Programming Experience
Beginner
Thank you!

Thank you for your reply. Can i know the code to do it? Thank!
 

Paszt

Staff member
Joined
Jun 3, 2004
Messages
1,500
Location
Raleigh, NC - USA
Programming Experience
Beginner
Here is some code that set the text property of a textbox named txtAddress to the address field from the database given the name as entered in a textbox named txtName. The database I've used is an Access database. If you use a different type of database, the connection string will differ and you may need to use the SqlCommand (as opposed to the OleDbCommand). Put this statement at the top of the code page: Imports System.Data.OleDb (or Imports System.Data.SqlClient, depending on the type of database.)

VB.NET:
Dim objConnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
  "Data Source=\somepath\mydb.mdb;User Id=admin;Password=;")
Dim strSQL As String
strSQL = "SELECT Address FROM mydatabase WHERE Name='" & txtName.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(strSQL, cnn)
Try
    objConnection.Open()
    txtAddress.Text = cmd.ExecuteScalar
Finally
    Try
        objConnection.Close()
    Catch : End Try
End Try
If you have further questions regarding databases (or anything else really), it's best to give more background information regarding the application you're attempting to design :).
 
Top Bottom