如何不将数据网格视图中的空行插入到sql表vb.net中

时间:2017-01-01 20:15:20

标签: vb.net

我有一个数据网格视图,我在其中插入数据。当我键入一行时,它会自动打开一个新行,这很好,但它会将空行插入数据库。

如何不将其插入数据库。

我的代码:

con.Open()
    For Each rw As DataGridViewRow In dgv_Deductions.Rows
        cmd = New SqlCommand("insert into SalDeduction (EmpNo, DeductionMonth,DeductionType,Amount,Remarks,tDate) values (" & txt_EmpNo.Text & ",'" & cmb_PaymentMonth.Text & "','" & rw.Cells(0).Value & "','" & rw.Cells(1).Value & "','" & rw.Cells(2).Value & "','" & Now() & "') ", con)
        cmd.ExecuteNonQuery()
    Next
    con.Close()

1 个答案:

答案 0 :(得分:1)

要按照要求回答您的问题,您可以这样做:

For Each row In DataGridView1.Rows.
                              Cast(Of DataGridViewRow)().
                              Where(Function(dgvr) Not dgvr.IsNewRow)
    '...
Next

我强烈建议不要这样做。您最好创建一个DataTable并将其绑定到网格,然后使用数据适配器保存批量中的所有更改。您可以手动构建DataTable,例如

Private table As DataTable

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    With Me.table.Columns
        .Add("ID", GetType(Integer))
        .Add("Name", GetType(String))
    End With

    Me.DataGridView1.DataSource = Me.table
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Using connection As New SqlConnection("connection string here"),
          command As New SqlCommand("INSERT INTO MyTable (ID, Name) VALUES (@ID, @Name)", connection),
          adapter As New SqlDataAdapter With {.InsertCommand = command}
        '...

        adapter.Update(Me.table)
    End Using
End Sub

或者,您可以使用数据适配器构建表格,例如

Private table As DataTable
Private adapter As SqlDataAdapter
Private builder As SqlCommandBuilder

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.table = New DataTable
    Me.adapter = New SqlDataAdapter("SELECT * FROM MyTable", "connection string here") With {.MissingSchemaAction = MissingSchemaAction.AddWithKey}
    Me.builder = New SqlCommandBuilder(Me.adapter)

    Me.adapter.FillSchema(Me.table, SchemaType.Source)
    Me.DataGridView1.DataSource = Me.table
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.adapter.Update(Me.table)
End Sub

该示例使用命令构建器,但如果您愿意,也可以自己构建InsertCommand