I ran into an interesting problem. When I add only one DataGridViewRow to a DataGridView everything works as expected: DataGridView.Rows[0] is the row that was added. When I add a second DataGridviewRow somehow the actual DataGridViewRows are no longer added but clones are added instead. Clones which seem perfectly the same but aren't in fact the same object.
So what I'd like to know is why this is, where this behavior comes from and if possible how to stop the clones from being added instead of the actual rows. I looked over the code for a DataGridViewRowCollection with Reflector but couldn't find anything fishy - but perhaps I missed something.
Here's a code sample that replicates the problem:
DataGridView dgv = new DataGridView { AllowUserToAddRows = false };
DataGridViewTextBoxColumn dgColumn = new DataGridViewTextBoxColumn();
dgv.Columns.Add(dgColumn);
DataGridViewRow drFirst = new DataGridViewRow();
dgv.Rows.Add(drFirst); // Comment this line to showcase the problem
DataGridViewRow drSecond = new DataGridViewRow();
drSecond.Tag = new object();
dgv.Rows.Add(drSecond);
// When drFirst is added this is false - when it isn't this is true (as it should always be?)
bool thisSeemsWrong = object.ReferenceEquals(dgv.Rows[dgv.Rows.Count - 1], drSecond);
// Always true
bool thisSeemsRight = object.ReferenceEquals(dgv.Rows[dgv.Rows.Count - 1].Tag, drSecond.Tag);
false
(using VB.NET).