开发者

How to get a datagrid cell values

开发者 https://www.devze.com 2022-12-21 06:21 出处:网络
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 & \"\', \'\" &am

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开发者_StackOverflow社区 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.


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:


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消