在数据库中通过datagrid插入数据时遇到问题

时间:2015-12-16 09:31:58

标签: vb.net

当我通过datagrid在数据库中插入数据时,数据正在插入,但数据库中还有一个空白行

我的代码: -

Private Sub Button2_Click(发件人作为对象,e作为EventArgs)处理Button2.Click

    con()

    Dim SNo As String
    Dim Name As String
    Dim Address As String

    For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1

        If Me.DataGridView1.Rows.Count = 0 Then

            Exit For

        End If

        SNo = Me.DataGridView1.Rows(i).Cells(0).Value
        Name = Me.DataGridView1.Rows(i).Cells(1).Value
        Address = Me.DataGridView1.Rows(i).Cells(2).Value


        Dim sql As String = "insert into Customer(SNo,Name,Address)values('" & SNo & "','" & Name & "','" & Address & "')"

        cmd = New SqlCommand(sql, cn)

        cmd.ExecuteNonQuery()

    Next

    MsgBox("Inserted")

    cn.Close()


End Sub

1 个答案:

答案 0 :(得分:0)

执行循环直到Datagridview1.rows.count-2

For i As Integer = 0 To Me.DataGridView1.Rows.Count - 2

    If Me.DataGridView1.Rows.Count = 0 Then

        Exit For

    End If

    SNo = Me.DataGridView1.Rows(i).Cells(0).Value
    Name = Me.DataGridView1.Rows(i).Cells(1).Value
    Address = Me.DataGridView1.Rows(i).Cells(2).Value


    Dim sql As String = "insert into Customer(SNo,Name,Address)values('" & SNo & "','" & Name & "','" & Address & "')"

    cmd = New SqlCommand(sql, cn)

    cmd.ExecuteNonQuery()

Next