how to bind arraylist to datagridview

W

weird0

Purpose: The objective is to update or add a new row in datagridview
using an arraylist

I have an arraylist inside of a class and i added an object to the
arraylist on the button click event. Then, after clearing the
datagridview1, i re-assigned the arraylist to the datasource property.
But it does not work, since the application crashes. The code goes
something like this:

Node n1=new Node();
State st1=new State("State",1);
n1.statesList.Add(s1);
datagridview1.DataBindings.Clear();
datagridview1.Refresh();
datagridview1.Datasource=n1.stateList; // Damn!!!! it crashes ..

Need help
Amir Diwan
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

You can bind almost any collection to an grid.
What error are you getting?

The most common error is an incorrect name of a column/property
 
M

Marc Gravell

First, check your columns ;-p

However, since you are using DataGridView (and hence 2.0) the easiest
answer might actually be to move to List<T> (for suitable T) - for
reasons that I will explain:

First; two questions:
Have you got mixed data? (i.e. different types of objects in the
ArrayList)
Is your ArrayList empty when you bind it?

Binding to lists expects the list contents to be similar. This is
particularly important with grids for obvious reasons.
The binding code works by checking a series of interfaces, including
IListSource, ITypedList, etc. Near the end of possibilities, are:
* IList and a typed indexer (not object)
* IList and at least on row

ArrayList (being untyped) fails the first of my bullets, so it has to
check for contents; it then has to assume that the first (zeroth,
depending on your perspective) item in the list is similar, so it uses
the Type of this item to infer the properties (via
TypeDescriptor.GetProperties(item[0].GetType() IIRC). Of course, it
can only do this if there is something in the list.
List<T>, by contrast, has a typed indexer "public T this[int index]
{...}"; this means that can stop at the first bullet, using (loosely)
TypeDescriptor.GetProperties(typeof(T)).

As such, the typed lists are significantly more reliable for binding.
Plus it may save you significant grief during development as you get
much better IDE support and need to do less casting.

Without more info I can't say for sure if this will help, but it is
worth a shot.

Finally, if you want real-time updates from objects (multiple views),
try using BindingList<T> assuming that your T implements
INotifyPropertyChange.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top