DataGridView多行选择,具体列数据获取

时间:2012-04-23 17:42:59

标签: vb.net datagridview

所以我有一个datagridview用数据库中的数据填充。 此时,用户可能会或可能不会(通过鼠标单击/按键)选择datagridview中的一行或多行。

我需要(在选择时)创建一个新的数据集,数据表并添加包含来自所述datagridview的一些数据的行。

例如,如果一个表只有名称,例如

Joe
Sean
Larry
Chris

用户点击后,在Sean和Larry上拖动选区,将这些名称添加到新数据集中,以便将其传递给其他方法进行进一步处理。

我就在这里。

    'Get index of current row
    Dim currentMouseRow As New Integer
    currentMouseRow = dataGridView_UnAssodevices.HitTest(e.X, e.Y).RowIndex


    'grab cell data of selected rows
    Dim ds As New DataSet
    Dim dt As New DataTable
    For Each row As DataGridViewRow In dataGridView_UnAssodevices.SelectedRows
        Dim dr As New DataGridViewRow
        Dim data As New DataGridViewTextBoxCell
        data.Value = row.Cells(0).Value
        dr.Cells.Add(data)
        dt.Rows.Add(dr)
        MessageBox.Show(data.ToString)
    Next





    'Add contextmenu if right clicked
    If e.Button = MouseButtons.Right Then
        Dim m As New ContextMenu()
        If currentMouseRow >= 0 Then
            dataGridView_UnAssodevices.Rows(currentMouseRow).Selected = True
            m.MenuItems.Add(New MenuItem("View Full Device Info"))
            m.MenuItems.Add(New MenuItem("Associate Device(s)"))
        End If
        m.Show(dataGridView_UnAssodevices, New Point(e.X, e.Y))
    End If

但是我一直收到这个错误:

 Input array is longer than the number of columns in this table.

看起来我要么缺少列声明,要么将表添加到集合中?

1 个答案:

答案 0 :(得分:0)

似乎您还没有为DataTable创建DataColumn。让我们试试

'Get index of current row
Dim currentMouseRow As New Integer
currentMouseRow = dataGridView_UnAssodevices.HitTest(e.X, e.Y).RowIndex


'grab cell data of selected rows
Dim ds As New DataSet
Dim dt As New DataTable

'Create a Data Column for your DataTable; Or you can write a loop to create the datacolumn based on the cell in your DataGridViewRow
dt.Columns.add("Col1")

For Each row As DataGridViewRow In dataGridView_UnAssodevices.SelectedRows
    Dim dr As New DataGridViewRow
    Dim data As New DataGridViewTextBoxCell
    data.Value = row.Cells(0).Value
    dr.Cells.Add(data)
    dt.Rows.Add(dr)
    MessageBox.Show(data.ToString)
Next