0

I've come across a rather strange behavior.

Behind my form i have my constructor which looks like this:

Private Property SourceDatatable As DataTable
Public Sub New()
     ' This call is required by the designer.
     InitializeComponent()

     SourceDatatable  = GetData()
     'SourceDatatable now has 500 rows
     AvailableObjects.DataSource = SourceDatatable 
End Sub

Right now all 500 rows are visible inside the gridview. When the user clicks a button, then the selected row is 'copied'

Private Sub CopyObject_Click(sender As System.Object, e As System.EventArgs) Handles AddNewObject.Click
    Dim selectedRow As Integer = GridviewAvailableObjects.GetSelectedRows().FirstOrDefault()
    If (selectedRow > 0) Then
        Dim selectedDataRow As Integer = GridviewAvailableObjects.GetRowHandle(selectedRow)
        SelectedRecords.Rows.Add(SourceDatatable.Rows(selectedDataRow))
    End If
    GridViewSelectedValues.RefreshData()
End Sub

The error occurs at SourceDatatable.Rows(selectedDataRow). All of a sudden it has 0 rows, Yet selectedDataRow refers to the correct row in the datasource(datatable). There is no interference of other Methods/Code as these 2 methods are the only ones present on the form and there is no other code on this form. Nor is the grid or any control accessible from outside the form.

What could cause this strange behavior? Does de Devexpress Gridview do anything with the datasource?

User999999
  • 2,500
  • 7
  • 37
  • 63

1 Answers1

1

You should not directly add rows from one table to another due to DataTable restrictions - it will throw the System.ArgumentException ("This row already belongs to another table") exception. This issue is not specific to DevExpress GridView. And you can avoid it with easy via copying only "values" from the original row into another table.

This version of "copying" works to me, please review it:

void btnCopy_Click(object sender, EventArgs e) {
    var selectedRowHandles = gridViewForAllData.GetSelectedRows();
    for(int i = 0; i < selectedRowHandles.Length; i++) {
        var selectedRow = gridViewForAllData.GetDataRow(selectedRowHandles[i]);
        selectedRowsTable.Rows.Add(selectedRow.ItemArray);
    }
    gridViewForSelectedValues.RefreshData();
}

VB.Net:

Private Sub btnCopy_Click(ByVal sender As Object, ByVal e As EventArgs) Handles simpleButton1.Click
    Dim selectedRowHandles = gridViewForAllData.GetSelectedRows()
    For i As Integer = 0 To selectedRowHandles.Length - 1
        Dim selectedRow = gridViewForAllData.GetDataRow(selectedRowHandles(i))
        selectedRowsTable.Rows.Add(selectedRow.ItemArray)
    Next i
    gridViewForSelectedValues.RefreshData()
End Sub
Community
  • 1
  • 1
DmitryG
  • 17,677
  • 1
  • 30
  • 53