简体   繁体   English

从datagridview向datatable添加行

[英]Adding rows to datatable from datagridview

i have a datagridview with a checkbox column.Now i have this code to add data from the dgvw to the datatable... 我有一个带复选框列的datagridview。现在我有这段代码可以将dgvw中的数据添加到数据表中...

 Dim dt As New DataTable
Dim r As DataRow

dt.Columns.Add("a", Type.GetType("System.String"))
dt.Columns.Add("b", Type.GetType("System.String"))
dt.Columns.Add("c", Type.GetType("System.String"))
dt.Columns.Add("d", Type.GetType("System.String"))

For i = 0 To dgvCarAccidentInjury.Rows.Count - 1
    r = dt.NewRow
    r("a") = dgvCarAccidentInjury.Item(0, i).Value.ToString
    r("b") = dgvCarAccidentInjury.Item(1, i).Value.ToString
    r("c") = dgvCarAccidentInjury.Item(2, i).Value.ToString
    r("d") = dgvCarAccidentInjury.Item(3, i).Value.ToString
    dt.Rows.Add(r)
Next

Now, what i want is, when i check a row's checkbox, then the currentrow/checkedrow would be added to the datatable.What changes should i make to do so ? 现在,我想要的是,当我选中某行的复选框时,那么currentrow / checkedrow将被添加到数据表中。我应该对此进行哪些更改? and in which even't should i apply the code ? 我什至不应该在其中应用代码? should i use the code in the row prepaint event ? 我应该在行预涂事件中使用代码吗? or currentcelldirtystatechanged event ? 还是currentcelldirtystatechanged事件?

you must write a method triggered by click event: 您必须编写由click事件触发的方法:

Dim dt As New DataTable
Dim r As DataRow

sub new()

    dt.Columns.Add("a", Type.GetType("System.String"))
    dt.Columns.Add("b", Type.GetType("System.String"))
    dt.Columns.Add("c", Type.GetType("System.String"))
    dt.Columns.Add("d", Type.GetType("System.String"))


end sub





Private Sub Grid1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvCarAccidentInjury.CellContentClick
    If e.ColumnIndex < 0 OrElse e.RowIndex < 0 Then Exit Sub

    Dim col = dgvCarAccidentInjury.Columns(e.ColumnIndex)
    Dim row = dgvCarAccidentInjury.Rows(e.RowIndex)
    If col.Name = "name_of_dgvcolumn_checkbox" Then
        Dim chkCell = DirectCast(row.Cells("name_of_dgvcolumn_checkbox"), DataGridViewCheckBoxCell)

        dr.rows.clear()

       For i = 0 To dgvCarAccidentInjury.Rows.Count - 1
          if chkCell then
         r = dt.NewRow
          r("a") = dgvCarAccidentInjury.Item(0, i).Value.ToString
          r("b") = dgvCarAccidentInjury.Item(1, i).Value.ToString
          r("c") = dgvCarAccidentInjury.Item(2, i).Value.ToString
          r("d") = dgvCarAccidentInjury.Item(3, i).Value.ToString
          dt.Rows.Add(r)
         end if
      Next


    End If
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM