Link to home
Start Free TrialLog in
Avatar of Russ Suter
Russ Suter

asked on

Weird DataGridView Behavior

I can't understand why this happens. I have a page level variable that stores an object I call EventCollection. That object contains a List<> of things. I use the code below to bind the list to a DataGridView.
this.dataGridViewEvents.DataSource = null;
if (this.EventCollection.List.Count > 0)
{
    // Don't assign an empty List<> to a DataGridView DataSource. It causes weirdness when selecting rows if they're added later.
    this.dataGridViewEvents.DataSource = this.EventCollection.List;
}

Open in new window

Later on if I want to add a new item I simply do this:
SierraEvent newEvent = new SierraEvent(this.ParentId);
this.EventCollection.Add(newEvent);

Open in new window

Then I rebind the datasource to the DataGridView control. This works fine as long as I make sure not to assign an empty list as the datasource. If I do that then I get a very odd behavior. After adding items to an empty list, if I then select a row in the DataGridView I get the following Exception:
System.IndexOutOfRangeException occurred
  _HResult=-2146233080
  _message=Index -1 does not have a value.
  HResult=-2146233080
  IsTransient=false
  Message=Index -1 does not have a value.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)
  InnerException: 

Open in new window

I've managed to avoid the problem using the above logic but I am at a loss to understand why this happens in the first place. Is this a bug in the DataGridView control?
Avatar of zephyr_hex (Megan)
zephyr_hex (Megan)
Flag of United States of America image

Just to confirm  -- after this:

this.dataGridViewEvents.DataSource = this.EventCollection.List;

Open in new window


you then actually do the bind, right?

this.dataGridViewEvents.DataBind();

Open in new window


Also, on the grid view control, do you have AppendDataBoundItems set to true or false?
Avatar of Russ Suter
Russ Suter

ASKER

There is no DataBind() method in the DataGridView control. Nor is there an AppendDataBoundItems property.
ASKER CERTIFIED SOLUTION
Avatar of it_saige
it_saige
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial