1

所以我有一个 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.

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

4

1 回答 1

0

似乎您还没有为您的数据表创建数据列。我们试试看

'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
于 2012-04-24T07:03:32.610 回答