tags:

views:

358

answers:

2

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.

A: 

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();
}
Arthur
@Arthur - In Insert Statement, How can i give the value like datagrid.rows(0).cell(0).value means it will take first row only or all rows?
Gopal
+1  A: 

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:

Dog Ears