如何在DataGridView中循环

时间:2014-05-08 07:59:38

标签: vb.net

如何使用VB.Net或C#.Net循环遍历所有行以将每个单元格存储为SQL表中的列?

//编码

    If cn.State = ConnectionState.Closed Then
        cn.Open()
    End If
    cmd = New SqlCommand("INSERT INTO TestTable VALUES (@Name, @Name1,@fname,@fname1)",cn)

    cmd.Parameters.AddWithValue("@name", DataGridView1.Rows(0).Cells(0).Value)
    cmd.Parameters.AddWithValue("@name1", DataGridView1.Rows(0).Cells(1).Value)

    cmd.Parameters.AddWithValue("@fname", DataGridView1.Rows(1).Cells(0).Value)
    cmd.Parameters.AddWithValue("@fname1", DataGridView1.Rows(1).Cells(1).Value)
    cmd.ExecuteNonQuery()
    MessageBox.Show("New Record Saved Successfully!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information)

2 个答案:

答案 0 :(得分:0)

For i=0 to DataGridView1.Rows.Count-1
cmd = New SqlCommand("INSERT INTO TestTable VALUES (@Name, @Name1,@fname,@fname1)",cn)
    cmd.Parameters.AddWithValue("@name", DataGridView1.Rows(i).Cells(0).Value)
    cmd.Parameters.AddWithValue("@name1", DataGridView1.Rows(i).Cells(1).Value)
    cmd.ExecuteNonQuery()
Next

答案 1 :(得分:0)

Dim InsertCommands() = {"@name","@name1","@fname","@fname1"}
Dim InsertCommandsIndex As Integer = 0

For Count1 = 0 To DataGridView1.ColumnCount - 1
    For Count2 = 0 To DataGridView1.RowCount - 1
        cmd.Parameters.AddWithValue(InsertCommands(InsertCommandsIndex), DataGridView1.Rows(Count2).Cells(Count1).Value)
        InsertCommandsIndex  +=1
    Next
Next
cmd.ExecuteNonQuery()