1
votes

So I have a datagridview being populated with data from a database. At this point a user may or may not selected (via mouse click / key press) one or more rows within the datagridview.

I need to (upon selection) create a new dataset, datatable and add rows with the some data from the said datagridview.

For example, if a table had nothing but names, e.g.

Joe
Sean
Larry
Chris

Upon the user clicking, dragging a selection over Sean and Larry to add those names to a new dataset so I can pass it to another method for further processing.

Here is where I am at.

    '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

However I keep getting this error:

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

It looks like I'm either missing a column declaration or adding the table to the set?

1

1 Answers

0
votes

Seems you haven't created the DataColumn for your DataTable. Lets try

'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