0
votes

when i insert data through datagrid in a database data's are inserting but an additional blank row is also coming in the data base

My Code:-

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles 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

1 Answers

0
votes

Execute the loop till 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