I have a windows form with a DataGridView
control.
I bound it into an attached DB file (.mdf).
I perform insertion by generating a dynamic Insert st
First of all, you have to use SQLCommand
and Parameters
to avoid sql injection since you are using SQLClient
namespace. Try this as your Insert
procedure.
Private Sub InsertSQL(ByVal param1 As String, ByVal param2 As String, ByVal param3 As String)
Using sqlConn As New SqlConnection("ConnectionStringHere")
Using sqlComm As New SqlCommand()
sqlComm.Connection = sqlConn
sqlComm.CommandType = CommandType.Text
sqlComm.CommandText = "INSERT INTO theTable VALUES (@Param1,@Param2,@Param3,@Param4,@Param5)"
With sqlComm.Parameters
.AddWithValue("@Param1", param1)
.AddWithValue("@Param2", param2)
.AddWithValue("@Param3", param3)
.AddWithValue("@Param4", Now)
.AddWithValue("@Param5", Now)
End With
Try
sqlConn.Open()
sqlComm.ExecuteNonQuery()
Catch ex As SqlException
MsgBox(ex.Message.ToString, MsgBoxStyle.Exclamation, "Error No. " & ex.ErrorCode.ToString)
Finally
sqlConn.Close()
End Try
End Using
End Using
End Sub
Secondly, why don't you prefer to use DataTable
to bind your DataGridView
? Well, here's another solution. It's ny using SQLDataReader
and you have to loop on it to put the records in your grid.
Private Sub ReloadGrid(ByVal connectionString As String)
Dim queryString As String = "Your Query Here"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
DataGridView1.Rows.Clear() ' Clear All Rows '
While reader.Read()
' Console.WriteLine(String.Format("{0}, {1}", reader(0), reader(1))) '
' Insert the record in your datagrid '
Dim row As String() = New String() {reader(0).ToString, reader(1).ToString, reader(2).ToString}
DataGridView1.Rows.Add(row)
End While
' Call Close when done reading. '
reader.Close()
End Using
End Sub