Reputation: 11982
Using VB.Net
I want to get a all datagrid cell values, then insert into table1.
Code
cmd = New SqlCommand("insert into table1 values('" & DataGrid.Rows(0).Cells(0).Value & "', '" & DataGrid.Rows(0).Cells(1).Value & "', '" & DataGrid.Rows(0).Cells(2).Value & "', '" & DataGrid.Rows(0).Cells(3).Value & "')", con)
cmd.ExecuteNonQuery()
The above code is inserting first row of datagrid cell value, but i want to insert all the datagrid cell values
How to modify my code for getting all the datagrid cell value.
Upvotes: 0
Views: 1743
Reputation: 10015
Sticking to your existing code, despite its flaws (definatly look up: SQL Injection)
You could do somthing like this:
For Each row As DataGridViewRow in dataGrid.Rows
cmd = New SqlCommand("insert into table1 values('" & row.Cells(0).Value & "', '" & row.Cells(1).Value & "', '" & row.Cells(2).Value & "', '" & row.Cells(3).Value & "')", con)
cmd.ExecuteNonQuery()
Next
There's numerous improvements that could be made but this answers your question:
Upvotes: 1
Reputation: 8129
First of all: avoid SQL Injection by using Parameters
Then: Loop over all rows and insert them
Pseudocode:
foreach(var row in DataGid.Rows)
{
insert();
}
Upvotes: 0