2

I know there are a couple of ways to create a new DataGridViewRow, see How to add a new row to datagridview programmatically
I am currently creating a class that inherits from DGVR, so I cannot let the DGV create it by just adding values, I must create it manually instead.
However, my code (written in C++/CLI) failed with ArgumentOutOfRangeException, so I tried with a normal DGVR and it also failed (method 1). Then I found a solution (method 2), but I don't understand why it works.
Is the original DGVR made invalid somehow after adding it to the DGV?

{
  ... 

  DataGridViewRow^ dgvrTest = gcnew DataGridViewRow();
  dgvrTest->CreateCells (dataGridView1);
  Object^ oValue = dgvrTest->Cells[0]->Value;  // okay

  int ixRow = dataGridView1->Rows->Add (dgvrTest);
  oValue = dataGridView1->Rows[ixRow]->Cells[0]->Value;  // okay

  // method #1
  oValue = dgvrTest->Cells[0]->Value;  // fails after adding the DGVR to the DGV

  // method #2
  dgvrTest = dataGridView1->Rows[ixRow];  // receives a different object. WHY?
  oValue = dgvrTest->Cells[0]->Value;  // works
}
Tobias Knauss
  • 3,361
  • 1
  • 21
  • 45
  • The language I used is C++/CLI, but it refers to C# in the same way. I will just add all .net tags now... – Tobias Knauss May 26 '17 at 14:49
  • I think this may have to do with shared rows - [docs](https://msdn.microsoft.com/en-us/library/75kfezas.aspx) say _"The Add(DataGridViewRow) method adds a shared row to the DataGridViewRowCollection, if possible. Otherwise, the new row is unshared"_. – stuartd May 26 '17 at 15:11
  • @stuartd: so, because `RowIndex` is -1 first, the row is shared, and then becomes unshared when adding it to the DGV, which makes the old row object invalid somehow. Makes sense. You may add an answer if you're sure about it. – Tobias Knauss May 26 '17 at 15:23

0 Answers0