How To do a search and Output to a datagrid Using VB.net
Posted on 2006-04-18
Hey guys how is everyone today?. Well I'm facing a small problem with my VB connection to Access.
I'm sure its simple, but I just can't see the error or why the error is occuring.
Anyhow my objective is to have a user input an ID from the 1 textbox, then have it Query to the Access DB
and display the information to a datagrid.
Keep in mind Im a noob with this kinda stuff since I barely know how to insert data to Access LOL
Well anyhow here is the code and tell me what you guys think of it?
The error Im getting is this ///// * An unhandled exception of type 'System.NullReferenceException' occurred in AlphaDesign.exe
Additional information: Object reference not set to an instance of an object.*///////
The code is this :
If txtUserID.Text = "" Then
MessageBox.Show("User ID Text Box is Empty!!", "Error", MessageBoxButtons.OK _
, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
lblUserIDError.Visible = True
lblUserIDError.Visible = False
'/////////////////////////////Here we will now try to FIND first the USer
Dim connString As String = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = X:\members.mdb;"
Dim myConnection As OleDbConnection = New OleDbConnection
Dim insertCmd As OleDbCommand ' This stores my Command for the DB
Dim UserID = txtUserID.Text.Trim
'Opening the DB connection
myConnection.ConnectionString = connString
'NOw to create a Select Command to search the DB
'Trying to put a search command with the user input from the text box
.Connection = myConnection //////****This is where the error occurs/////
.CommandText = "Select User_ID From UserTable" & _
"Where User_ID = UserID "
.CommandType = CommandType.Text
.Parameters("@User_ID").Value = UserID ' This is the textBox.
'Now to declare a OLEDBDataAdapter object
Dim Adapter As New OleDbDataAdapter
'Now to declare a dataset
Dim DataSet As New DataSet
'Now to apply my Command to the DataAdapter
Adapter.SelectCommand = insertCmd
Try ' The reason we use try is to see if the database can open and what can happen
'To bind the Dataset to the DataGrid :)
grdResults.DataSource = DataSet
'Tell the DataGrid which table in the Dataset to use
grdResults.DataMember = DataSet.Tables(0).TableName
'Setting the Alternating Colors property to the Grid
grdResults.AlternatingBackColor = Color.WhiteSmoke
'Set the GridLineStyle Property :)
grdResults.GridLineStyle = DataGridLineStyle.None
'Set the SelectionBackColor and the Selection ForeColor Properties
grdResults.SelectionBackColor = Color.LightGray
grdResults.SelectionForeColor = Color.Black
Catch OleDbExceptionErr As OleDbException
Catch InvalidOperationExceptionErr As InvalidOperationException
'Cleaning up the Mess
insertCmd = Nothing
Adapter = Nothing
DataSet = Nothing
myConnection = Nothing
Also I just wanted to know if my SQL is good or is that also messed up :(
Thankyou in advance as always and please let me know what you guys think.