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;
}
Later on if I want to add a new item I simply do this:SierraEvent newEvent = new SierraEvent(this.ParentId);
this.EventCollection.Add(newEvent);
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:
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?
ASKER
There is no DataBind() method in the DataGridView control. Nor is there an AppendDataBoundItems property.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Open in new window
you then actually do the bind, right?
Open in new window
Also, on the grid view control, do you have AppendDataBoundItems set to true or false?