BindingList and ArgumentOutOfRange when bound to DataGridView

  • Thread starter Thread starter Jim Balo
  • Start date Start date
J

Jim Balo

Hi,

When I bind a BindingList<> to a DataGridView and then call RemoveAt(n) on
it, I get ArgumentOutOfRange. Could someone explain why?

Sample:

public partial class TestForm2 : Form
{
private BindingList<Person> _personList = new BindingList<Person>();

public TestForm2()
{
InitializeComponent();
}

private void TestForm2_Load(object sender, EventArgs e)
{
Person personA = new Person("Pete");
Person personB = new Person("James");
_personList.Add(personA);
_personList.Add(personB);

uxTestGrid.DataSource = _personList;
}

private void uxTestButton_Click(object sender, EventArgs e)
{
_personList.RemoveAt(0);
}
}

public class Person
{
public string Name = "";
public Person(string name)
{
Name = name;
}
}

So I have two Person objects in the BindingList. Yet, when I call
_personList.RemoveAt(0) (or 1), I get this exception. If I do not bind it
to the DataGridView, it works fine.

Please help.

Thanks,
Jim
 
Hi Jim,

I'm not exactly sure of this, but I think because Person does not have any
properties it is not visible in the DataGridView, and internally the
DataGridView operates on an empty Person-list. When the datasource removes
one item the DataGridView does not have any items to remove.

If you add a property to Person, it should work fine.

public class Person
{
private string _name;

public string Name
{
get { return _name; }
set { _name = value; }
}

public Person(string name)
{
Name = name;
}
}
 
I'm not exactly sure of this, but I think because Person does not have any
properties it is not visible in the DataGridView, and internally the
DataGridView operates on an empty Person-list. When the datasource
removes
one item the DataGridView does not have any items to remove.

If you add a property to Person, it should work fine.

That was it! Actually, this was a test I did trying to debug a similar
problem with the DataGrid in the Compact framework (getting
ObjectDisposedException when removing an item). The title of that post is
"ObjectDisposedException with DataGrid" in case you or someone else here has
some suggestion.

Thanks for your help,
Jim
 
Back
Top