Checking existing table rows - vb.net

Can somebody tell me what I've done wrong inside my coding? I am trying to match the user login name and password with the one inside the database. If got row and matched then user will be able to login into the system but it seems like my system can only read the first row of my data table (inside database).
Here is my coding that I currently use.
Private Sub CheckLogin()
Dim lCnn As New SqlConnection
Dim lCmd As New SqlCommand
Dim lRd As SqlDataReader
Dim lsCmd As String
If TextBoxLogin.Text = "" Then
MsgBox("Enter your Username.")
Try
TextBoxLogin.Focus()
Catch ex As Exception
End Try
ElseIf TextBoxPass.Text = "" Then
MsgBox("Enter your Password.")
Try
TextBoxPass.Focus()
Catch ex As Exception
End Try
Else
lCnn.ConnectionString = GetConnString()
lCnn.Open()
lCmd.Connection = lCnn
lsCmd = "SELECT * FROM UserInfo..UserInfo "
lsCmd &= " INNER JOIN UserInfo..UserAccess ON UserLogin = UA_UserLogin "
lsCmd &= " WHERE (UserLogin = " & SQLQuote(Trim(TextBoxLogin.Text)) & " AND UserPassword = " & SQLQuote(Trim(TextBoxPass.Text))
lsCmd &= " AND UserActive = 1"
lsCmd &= " AND UA_AICode = 'MENU')"
lCmd.CommandText = lsCmd
lRd = lCmd.ExecuteReader()
If lRd.HasRows Then
lRd.Read()
lbLoginSuccess = True
gsLoginID = Trim(TextBoxLogin.Text)
gsUserPass = Trim(TextBoxPass.Text)
Me.Close()
Else
lnCurRetry += 1
Alert("Wrong Username or Password.")
End If
lRd.Close()
lCnn.Close()
End If
If Not lbLoginSuccess Then
If lnCurRetry >= 3 Then
Me.Close()
End If
End If
End Sub
I appreciate your help. Thanks.

Your code is not really bad, but can be better if utilize that sintax:
Using LCnn As New SqlConnection
LCnn.ConnectionString = GetConnString()
Try
LCnn.Open()
Using LCmd As New SqlCommand("SELECT * FROM UserInfo " & _
"INNER JOIN UserAccess ON UserLogin = UA_UserLogin " & _
"WHERE (UserLogin = '" & TextBoxLogin.Text.trim & "' " & _
"AND UserPassword = '" & TextBoxPass.Text.Trim & "' " & _
"AND UserActive = 1 AND UA_AICode = 'MENU')", LCnn)
Dim LRdr As SqlDataReader
Try
LRdr = SQL_Cmd.ExecuteReader
If Not SQL_Rdr.HasRows Then
msgbox("Empty Results...")
else
<your code>
endif
catch ex as Exception
msgbox("Error: " & ex.message)
end try
end using ' Lcmd
catch exConn as Exception
msgbox("Error: " & exConn.message)
end try
end using ' LCnn
Remember: the Using/End Using syntax can help you to manage resources. End Using always close and dispose resources.
Good luck

Related

How do I track down an Unclosed reader

I've got a utility function in a much larger project that updates a backend SQL database. It's currently failing most times I use it, with the error:
There is already an open DataReader associated with this Command which must be closed first.
The code for the function is below:
Public Function Update_Data(what As String, Optional where As String = "",
Optional table As String = ThisAddIn.defaultTable) As Integer
Try
Dim cmd As New SqlCommand With {
.Connection = conn
}
cmd.CommandText = "UPDATE " & table & " SET " & what
If where <> "" Then
cmd.CommandText &= " WHERE " & where
End If
Update_Data = cmd.ExecuteNonQuery
cmd.Dispose()
Catch ex As Exception
Update_Data = 0
Debug.WriteLine("SQL Error updating data:" & vbCrLf & ex.Message)
End Try
End Function
I've gone through the rest of the code to make sure that whenever I have a SQLDataReader declared I later call reader.close(). I added the cmd.Dispose() line to this and all the other ExecuteNonQuery functions I could find - incase that helped?
Are there any other instances/types of reader that might not be being closed?
In the case of an Exception, you aren't disposing your command.
If you don't want to use Using, add a Finally
Public Function Update_Data(what As String, Optional where As String = "",
Optional table As String = ThisAddIn.defaultTable) As Integer
Dim cmd As SqlCommand
Try
cmd = New SqlCommand With {.Connection = conn}
cmd.CommandText = "UPDATE " & table & " SET " & what
If where <> "" Then
cmd.CommandText &= " WHERE " & where
End If
Update_Data = cmd.ExecuteNonQuery
Catch ex As Exception
Update_Data = 0
Debug.WriteLine("SQL Error updating data:" & vbCrLf & ex.Message)
Finally
cmd.Dispose()
End Try
End Function
but Using might be simpler
Public Function Update_Data(what As String, Optional where As String = "",
Optional table As String = ThisAddIn.defaultTable) As Integer
Using cmd As New SqlCommand With {.Connection = conn}
Try
cmd.CommandText = "UPDATE " & table & " SET " & what
If where <> "" Then
cmd.CommandText &= " WHERE " & where
End If
Update_Data = cmd.ExecuteNonQuery
Catch ex As Exception
Update_Data = 0
Debug.WriteLine("SQL Error updating data:" & vbCrLf & ex.Message)
End Try
End Using
End Function

No value given for one or more required parameters (access)

I have 2 datatable with these fields
*dataordner
Archive Date/Time (datetimepicker, it's already data)
Storage Short Text (combobox)
BulanOrdner ShortText (combobox)
TahunOrdner Date/Time (datetimepicker)
*datalemari
Archive Date/Time (datetimepicker, it's already data)
Storage Short Text (combobox)
Lemari Short Text (combobox)
BulanOrdner ShortText (combobox)
TahunOrdner Date/Time (datetimepicker)
and now I am very confused why i'm wrong
What I have tried:
I've done with my codes but always error with that error "no value given for one more...."
I call 2 table with if else in combobox(storage)
These are my code sequences, i think that's all true with selected item in combobox
note:
storage = combobox
Private Sub storage_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles storage.SelectedIndexChanged
If storage.SelectedIndex = 1 Then
groupordner.Visible = True
grouplemari.Visible = False
Else
If storage.SelectedIndex = 2 Then
groupordner.Visible = False
grouplemari.Visible = True
End If
End If
End Sub
Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
If storage.SelectedItem = "Ordner" Then
str = "Update dataordner set Storage = " & storage.Text & ", BulanOrdner = " & bulanordner.Text & ", TahunOrdner = '" & tahunordner.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
proses.ExecuteNonQuery(str)
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
Else
If storage.SelectedItem = "Lemari" Then
str = "Update datalemari set Storage = " & storage.Text & ", Lemari = " & lemari.Text & ", BulanLemari = " & bulanlemari.Text & ", TahunLemari = '" & tahunlemari.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
proses.ExecuteNonQuery(str)
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
End If
End If
End Sub
There might me some control's value that is null or Nothing, you can use Debugging with Breakpoints to check null values Or there might be Objects that are not initialized.
You can also try the code below :
Note : I will recommend you to use Parameterized Query instead
Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
If storage.SelectedItem Is Nothing Then
MsgBox("Plese Select the item first", MsgBoxStyle.Exclamation)
Else
If conn.State <> ConnectionState.Open Then
conn.Open() '' Assuming conn is your OleDbConnection
End If
Dim cmd As OleDbCommand = conn.CreateCommand
Try
If storage.SelectedItem = "Ordner" Then
Str = "Update dataordner set Storage = " & storage.Text & ", BulanOrdner = " & bulanordner.Text & ", TahunOrdner = '" & tahunordner.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
cmd.CommandText = Str
cmd.ExecuteNonQuery()
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
Else
If storage.SelectedItem = "Lemari" Then
Str = "Update datalemari set Storage = " & storage.Text & ", Lemari = " & lemari.Text & ", BulanLemari = " & bulanlemari.Text & ", TahunLemari = '" & tahunlemari.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
cmd.CommandText = Str
cmd.ExecuteNonQuery()
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
End If
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation)
Finally
conn.Close()
End Try
End If
End Sub

Windows Mobile v 6.5 connecting to SQL Server 2008 R2

I have a problem connecting my windows mobile application developed using vb.net in my SQL server 2008 as my back end. Here is my connection string :
Data Source=STEPH-PC\SQL2008;Initial Catalog= MyDB; User ID = myusername; Password = mypassword;
It always give me an error that SQL server does not exist or access denied. Any help on how to solve this issue?
1- Testing connection Server versus Pocket PC:
First at all test if your SQL Server CE mobile agent connects to SQL Server CE Server agent. To do this you have to install SQL Server CE 3.5 in the server and in your Pocket PC. Search in google How to install SQL Server CE 3.5. In the process you create a Virtual Directory in Server and in that directory you got a file sqlcesa35.dll, so to test the connection in your Pocket PC browser write: http://ipserver/virtual_directory/sqlcesa35.dll (of course ipserver must be your server IP and virtual_directory must be your virtual directory name). Doing this you have to get in your Pocket PC the message:
Microsoft SQL Server Compact
Server Agent
At this point I have to mention that always you must have internet connection.
2- Retrieving files from the server (this is a sample code, not debugged, I only have taken some parts from other project and put them here).
Function get_companies(ByVal sSucursal As String, ByVal cn_Interface As System.Data.SqlServerCe.SqlCeConnection, _
ByVal cmd_Interface As System.Data.SqlServerCe.SqlCeCommand, ByVal dr_Interface As System.Data.SqlServerCe.SqlCeDataReader) As Boolean
get_companies = False
Dim _strRemoteConnect As String
Dim _strLocalConnect As String
Dim _strInternetURL As String = sInternetURL
'The last variable sInternetURL is something like: http://ip_server/virtual_directory/sqlcesa35.dll
_strRemoteConnect = "Provider=SQLOLEDB;Data Source=" & sIPSQLServer & ";Initial Catalog=" & sBDSQLServer & ";User Id=" & sUserSQLServer & ";Password=" & sClaveSQLServer
'sIPSQLServer is the server ip where is running SQL Server
'sBDSQLServer is your DataBase server.
_strLocalConnect = "Data Source=" & sPath & "\" & sDataBase_Interface & "; Password=" & sPassword
'sPath is your directory in your Pocket PC, begings with \
'sDataBase_Interface is the database in my Pocket PC, an .sdf file
Dim rda As System.Data.SqlServerCe.SqlCeRemoteDataAccess = New System.Data.SqlServerCe.SqlCeRemoteDataAccess
rda.InternetLogin = sUserInternet 'a valid user in your domain
rda.InternetPassword = sClaveInternet
rda.InternetUrl = _strInternetURL
rda.LocalConnectionString = _strLocalConnect
Do While True
Try
'In server database there is a table: Monedas
rda.Pull("_Monedas", "Select Moneda, Descripcion, Abreviada From Monedas Where Sucursal = '" & sSucursal & "'", _
_strRemoteConnect, System.Data.SqlServerCe.RdaTrackOption.TrackingOff)
Exit Do
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Loop
'read the data received, just testing, may be this code not to be here because you process the data outside the function.
Try
cmd_Interface.CommandText = "Select Moneda, Descripcion, Abreviada From _Monedas"
dr_Interface = cmd_Interface.ExecuteReader()
Do While dr_Interface.Read()
messagebox.show("Moneda = " & dr_interface("Moneda") & " - " & dr_interface("Descripcion") & " - " & dr_interface("Abreviada"), _
"Currencies Received", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
Loop
get_companies = true
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1)
Finally
'If cn_Interface.State <> ConnectionState.Closed Then
' cmd_Interface.Dispose()
' cn_Interface.Close()
' cn_Interface.Dispose()
'End If
End Try
End Function
3- Excecuting a sentence in Database Server from your Pocket PC and Transferring data from Pocket to Server:
Function EnviarClientesNuevos(ByVal sSucursal As String, ByVal sZona As String, ByVal sRuta As String) As Boolean
Dim sLineas As String
Dim nRegs As Integer
Dim cn_Interface As System.Data.SqlServerCe.SqlCeConnection
Dim cmd_Interface As System.Data.SqlServerCe.SqlCeCommand
EnviarClientesNuevos = False
Dim _strRemoteConnect As String
Dim _strLocalConnect As String
Dim _strInternetURL As String = sInternetURL
_strRemoteConnect = "Provider=SQLOLEDB;Data Source=" & sIPSQLServer & ";Initial Catalog=" & sBDSQLServer & ";User Id=" & sUserSQLServer & ";Password=" & sClaveSQLServer
_strLocalConnect = "Data Source=" & sPath & "\" & sDataBase_Interface & "; Password=" & sPassword
Dim rda As System.Data.SqlServerCe.SqlCeRemoteDataAccess = New System.Data.SqlServerCe.SqlCeRemoteDataAccess
rda.InternetLogin = sUserInternet
rda.InternetPassword = sClaveInternet
rda.InternetUrl = _strInternetURL
rda.LocalConnectionString = _strLocalConnect
Do While True
If DropTableE("_NEW_CLIENTES_XX") Then
Try
'_NEW_CLIENTES_XX is a table in your SQL Server (The server, not the Pocket)
rda.Pull("_NEW_CLIENTES_XX", "Select Id, Sucursal, Zona, CodCli, Nombre, Direccion, Ruc, Clase, Ruta " & _
"FROM _NEW_CLIENTES_XX WHERE Sucursal = ''", _strRemoteConnect, SqlServerCe.RdaTrackOption.TrackingOn)
'In where clause I compare to '' because I only need the structure
Exit Do
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Exit Function
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Function
End Try
End If
Loop
Try
'--
cn_Interface = New System.Data.SqlServerCe.SqlCeConnection
cn_Interface.ConnectionString = "Data Source=" & sPath & "\" & sDataBase_Interface & ";Password=" & sPassword
cn_Interface.Open()
cmd_Interface = cn_Interface.CreateCommand()
cmd_Interface.CommandType = CommandType.Text
'--
'here I have an open connection to another database in my Mobile Device. Here I have to mention that I work with 2 databases in my mobile device:
'One database for getting the data from server, I only use it when I get data from server and when I send data to server
'and other database which is my main database, the database that is used all the day storing customers transactions.
'here I already have open (outside this function) the connection to this second database, but the sentence are the same above,
'something like this:
'Try
' cn = New System.Data.SqlServerCe.SqlCeConnection
' cn.ConnectionString = "Data Source=" & sPath & "\" & sDataBase_Ppal & ";Password=" & sPassword
' cn.Open()
' cmd = cn.CreateCommand()
' cmd.CommandType = CommandType.Text
'Read the data from my main Pocket PC database
cmd.CommandText = "SELECT CodCli, Nombre, Direccion, Ruc, Clase From CLIENTES WHERE CLASE IN ('N', 'M')"
dr = cmd.ExecuteReader()
Do While dr.Read()
'Insert the data in the table structure that I get above.
'remember that this table is in the database that only is used when transferring data, its a temporal database.
cmd_Interface.CommandText = "INSERT INTO _NEW_CLIENTES_XX (Sucursal, Zona, CodCli, Nombre, Direccion, Ruc, Clase, Ruta) " & _
"VALUES('" & sSucursal & "', '" & sZona & "', " & dr("CodCli") & ", '" & _
dr("Nombre") & "', '" & dr("Direccion") & "', '" & dr("Ruc") & "', '" & _
dr("Clase") & "', '" & sRuta & "')"
nRegs = cmd_Interface.ExecuteNonQuery()
Loop
dr.Close() : dr.Dispose()
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Exit Function
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1)
Exit Function
Finally
Try
dr.Close()
dr.Dispose()
Catch ex As Exception
End Try
'If cn.State <> ConnectionState.Closed Then
' cmd.Dispose()
' cn.Close()
' cn.Dispose()
'End If
If cn_Interface.State <> ConnectionState.Closed Then
cmd_Interface.Dispose()
cn_Interface.Close()
cn_Interface.Dispose()
End If
End Try
Do While True
Try
'I excecute a sentence in the Server. I delete the data in _NEW_CLIENTES_XX which is a work table in SQL server.
rda.SubmitSql("Delete From _NEW_CLIENTES_XX Where Sucursal = '" & sSucursal & "' AND Zona = '" & sZona & "' And Ruta = '" & sRuta & "'", _strRemoteConnect)
'I send the data to server
rda.Push("_NEW_CLIENTES_XX", _strRemoteConnect, System.Data.SqlServerCe.RdaBatchOption.BatchingOn)
EnviarClientesNuevos = True
Exit Do
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Exit Function
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Function
End Try
Loop
End Function
Generalities:
Function DropTableP(ByVal sTabla As String) As Boolean
'Dim cn_Interface As System.Data.SqlServerCe.SqlCeConnection
'Dim cmd_Interface As System.Data.SqlServerCe.SqlCeCommand
'Dim dr_Interface As System.Data.SqlServerCe.SqlCeDataReader
Dim nRegs As Integer
Try
'cn_Interface = New System.Data.SqlServerCe.SqlCeConnection("Data Source=" & sPath & "\" & sDataBase_Ppal & "; Password=" & sPassword)
'cn_Interface.Open()
'cmd_Interface = cn_Interface.CreateCommand()
'cmd_Interface.CommandType = CommandType.Text
cmd.CommandText = "Select TABLE_NAME From INFORMATION_SCHEMA.TABLES Where TABLE_NAME = '" & sTabla & "'"
dr = cmd.ExecuteReader()
If dr.Read() Then
dr.Close()
dr.Dispose()
cmd.CommandText = "DROP TABLE " & sTabla
nRegs = cmd.ExecuteNonQuery()
DropTableP = True
Else
dr.Close()
dr.Dispose()
DropTableP = True
End If
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
'If cn_Interface.State <> ConnectionState.Closed Then
' cn_Interface.Close()
' cn_Interface.Dispose()
'End If
End Try
End Function
Sub ShowErrorSqlServerCE(ByVal exc As System.Data.SqlServerCe.SqlCeException)
Dim bld As New System.Text.StringBuilder
Dim err As System.Data.SqlServerCe.SqlCeError
Dim errorCollection As System.Data.SqlServerCe.SqlCeErrorCollection = exc.Errors
Dim errPar As String
Dim numPar As Integer
' Loop through all of the errors.
For Each err In errorCollection
bld.Append(ControlChars.Cr & " Error Code: " & err.HResult.ToString("X"))
bld.Append(ControlChars.Cr & " Message : " & err.Message)
bld.Append(ControlChars.Cr & " Minor Err.: " & err.NativeError)
bld.Append(ControlChars.Cr & " Source : " & err.Source)
' Loop through all of the numeric parameters for this specific error.
For Each numPar In err.NumericErrorParameters
If numPar <> 0 Then
bld.Append(ControlChars.Cr & " Num. Par. : " & numPar.ToString())
End If
Next numPar
' Loop through all of the error parameters for this specific error.
For Each errPar In err.ErrorParameters
If errPar <> [String].Empty Then
bld.Append(ControlChars.Cr & " Err. Par. : " & errPar)
End If
Next errPar
' Finally, display this error.
MessageBox.Show(bld.ToString(), "SQL Server CE")
' Empty the string so that it can be used again.
bld.Remove(0, bld.Length)
Next err
End Sub
As I said above: the code that I put here needs to be debugged...I have only extracted some parts from my project and put here. Hope this will help you!

ODBC - unable to allocate an environment handle

Hi I am trying to insert data into Navision database from a DataTable. That DataTable contain around 5000 records, if the records count is less then it's working fine but record count is around 5000 I am getting this error.
ERROR - unable to allocate an environment handle.
This is the code I am using
Public Function InsertToHHTTransferLine(ByVal dtTransferLn As DataTable, ByVal hhtNumber As String) As Integer
Dim result As Integer
Dim cn As OdbcConnection
Dim dtTransferLine As DataTable
cn = New OdbcConnection(ConnStr)
Dim SqlStr As String = ""
Try
cn.Open()
dtTransferLine = dtTransferLn
Dim DocType As String
DocType = "Purchase"
Dim cmd As OdbcCommand
Dim hhtNo As String
hhtNo = hhtNumber
If dtTransferLine.Rows.Count > 0 Then
For i As Integer = 0 To dtTransferLine.Rows.Count - 1
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "0" Then
DocType = "Purchase"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "1" Then
DocType = "Transfer Receipt"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "2" Then
DocType = "Transfer Shipment"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "3" Then
DocType = "Stock Count"
End If
Try
SqlStr = "INSERT INTO ""HHT & Navision Line""(""Document Type"",""Document No_"",""HHT No_"",""Line No_"",""Item No_"",""Document Quantity"",""Scan Quantity"",""Unit Price"",""Posted"") VALUES('" & DocType & "','" & dtTransferLine.Rows(i)("DOC_NO").ToString() & "','" & hhtNo & "','" & dtTransferLine.Rows(i)("LINE_NO").ToString() & "','" & dtTransferLine.Rows(i)("ITEM_NO").ToString() & "'," & dtTransferLine.Rows(i)("DOC_QTY").ToString() & "," & dtTransferLine.Rows(i)("SCAN_QTY").ToString() & "," & dtTransferLine.Rows(i)("UNIT_PRICE").ToString() & ",0)"
cmd = New OdbcCommand(SqlStr, cn)
result = cmd.ExecuteNonQuery()
Catch ex As Exception
If (ex.Message.IndexOf("Illegal duplicate key") <> -1) Then
CreateLog(SqlStr, "User1", "Duplicate()", ex.Message)
Else
CreateLog(SqlStr, "User1", "Other()", ex.Message)
End If
'CreateLog(SqlStr, "User1", "Other()", ex.Message)
End Try
Next
End If
Catch ex As Exception
CreateLog(SqlStr, "User1", "InsertToHHTTransferLine()", ex.Message)
result = -1
Finally
cn.Close()
cn.Dispose()
End Try
Return result
End Function
Could be that "cmd" variables need to be disposed before creating new ones?
At least this is the only thing I can see in the code where you are consuming resources in a loop depending on the number of records.
Anyway this should be easy to identify with a debugger, just figure out the line giving you the error, and that will lead you to the answer.

Filling values in DataGridView

I want to display result of select query in a DataGridView with where clause in query. The condition is specified in a label's value. i.e
select *
from hospital_details
where location_name= '" & Label6.Text & "'"
Following is the code
Public Sub fill()
Try
createConnection()
da = New SqlDataAdapter
Dim c As String
c = Label6.Text
comm.CommandText = "select * from hospital_details where location_name= '" & Label6.Text & "'"
da.SelectCommand = comm
da.Fill(ds, "hospital_details")
DataGridView2.DataSource = ds.Tables(0)
DataGridView2.DataMember = "hospital_details"
DataGridView2.ReadOnly = True
Catch ex As Exception
MsgBox("Error: " & ex.Source & ": " & ex.Message, MsgBoxStyle.OkOnly, "Connection Error !!")
End Try
End Sub
But its showing error : NullException
You can load data from sql server , follow the link
http://mssqlguid.blogspot.in/2013/07/how-to-load-data-into-datagridview-from.html