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 statement. I then pump this sql statement into a SqlCommand object and perform ExecuteNonQuery() method. All of these is performed by handling a Button click event. The button and the gridview is located on the same form.
Public Sub InsertRow(ByVal param1 As String, ByVal param2 As String, ByVal param3 As String)
Dim strConn As String = (the connection string)
Dim sqlConn As New SqlConnection(strConn)
Dim insertSQL As String = "INSERT INTO theTable VALUES ('" + param1 + "', '" + param2 + "', '" + param3 + "', '" + DateTime.Now + "', '" + DateTime.Now + "')"
Dim comm As New SqlCommand(insertSQL, sqlConn)
sqlConn.Open()
comm.ExecuteNonQuery()
sqlConn.Close()
End Sub
Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
InsertRow("a","b","c")
End Sub
After the code execution, the DataGridView is not updating (remains intact). I have to exit the form and reload it to have the updated gridview.
For certain reasons, I can’t use DataTable object.
But I would like to have this gridview updated everytime I run the insertion.
Can someone tell me how to do it?
Thank’s
P.S Although I am doing this in VB, I don’t mind receiving answer in C#
First of all, you have to use
SQLCommandandParametersto avoid sql injection since you are usingSQLClientnamespace. Try this as yourInsertprocedure.Secondly, why don’t you prefer to use
DataTableto bind yourDataGridView? Well, here’s another solution. It’s ny usingSQLDataReaderand you have to loop on it to put the records in your grid.