This tutorial is kind of a follow-up to my previous tutorial about binding a DataGridView to an Access database. In this tutorial, I'm going to demonstrate how to bind a DataGridView to a regular old .NET collection.
Before we can build a collection of objects, we first need an object. I tend to use a Car object for most of my examples. The car object simply holds some information about a typical car - make, model, and year. Below is the object I'm going to use.
{
private string _make;
private string _model;
private int _year;
public Car(string make, string model, int year)
{
_make = make;
_model = model;
_year = year;
}
public string Make
{
get { return _make; }
set { _make = value; }
}
public string Model
{
get { return _model; }
set { _model = value; }
}
public int Year
{
get { return _year; }
set { _year = value; }
}
}
All right, now that we've got an object, we need a collection to hold them. One of my favorite collection objects is the List, located in the System.Collections.Generic namespace, so we'll start with that.
cars.Add(new Car("Ford", "Mustang", 1967));
cars.Add(new Car("Shelby AC", "Cobra", 1965));
cars.Add(new Car("Chevrolet", "Corvette Sting Ray", 1965));
Binding this to a DataGridView is painfully easy. Simply set the DataSource property of the DataGridView to the List.
What will happen is that the DataGridView will automatically create columns for each property in the Car object, then create a row for each Car in the List. What we've created here is one-way binding. Any changes made by the user in the DataGridView will also take place in the List. If we want changes made to a Car to update the DataGridView, the Car object will have to implement the INotifyPropertyChanged interface.
{
private string _make;
private string _model;
private int _year;
public event PropertyChangedEventHandler PropertyChanged;
public Car(string make, string model, int year)
{
_make = make;
_model = model;
_year = year;
}
public string Make
{
get { return _make; }
set
{
_make = value;
this.NotifyPropertyChanged("Make");
}
}
public string Model
{
get { return _model; }
set
{
_model = value;
this.NotifyPropertyChanged("Model");
}
}
public int Year
{
get { return _year; }
set
{
_year = value;
this.NotifyPropertyChanged("Year");
}
}
private void NotifyPropertyChanged(string name)
{
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
Unfortunately, this won't be enough. The List class does not support notifications from objects within its collection. Fortunately, there is an object that does - the BindingList. For the most part, the BindingList is used exactly like a List.
cars.Add(new Car("Ford", "Mustang", 1967));
cars.Add(new Car("Shelby AC", "Cobra", 1965));
cars.Add(new Car("Chevrolet", "Corvette Sting Ray", 1965));
_dgCars.DataSource = cars;
Now, if any external process, like a network thread, makes a change to a Car object, the DataGridView will automatically update to reflect the change.
Now we've got data in the DataGridView and any changes to the UI or the List will automatically update the other. Usually my properties aren't named something that are so user friendly. What happens when I want my columns named something else? This can be easily accomplished by disabling the AutoGenerateColumns property and by setting up the columns ourselves.
DataGridViewTextBoxColumn makeColumn = new DataGridViewTextBoxColumn();
makeColumn.DataPropertyName = "Make";
makeColumn.HeaderText = "The Car's Make";
DataGridViewTextBoxColumn modelColumn = new DataGridViewTextBoxColumn();
modelColumn.DataPropertyName = "Model";
modelColumn.HeaderText = "The Car's Model";
DataGridViewTextBoxColumn yearColumn = new DataGridViewTextBoxColumn();
yearColumn.DataPropertyName = "Year";
yearColumn.HeaderText = "The Car's Year";
_dgCars.Columns.Add(makeColumn);
_dgCars.Columns.Add(modelColumn);
_dgCars.Columns.Add(yearColumn);
BindingList<Car> cars = new BindingList<Car>();
cars.Add(new Car("Ford", "Mustang", 1967));
cars.Add(new Car("Shelby AC", "Cobra", 1965));
cars.Add(new Car("Chevrolet", "Corvette Sting Ray", 1965));
_dgCars.DataSource = cars;
Setting up the columns is pretty straight forward. There's all types of DataGridViewColumns, but I went with the basic TextBox version. All you have to do it set the HeaderText, which is what the user will see, and the DataPropertyName, which is the name of the property of the object that is bound to the DataGridView. Here's what our DataGridView looks like now:
I think that does it for binding a collection to a DataGridView. Data binding is a very powerful tool and we haven't even begun scratching the surface. If you have any questions leave us a comment.
05/06/2008 - 09:44
Look forward to reading more about WinForm and binding, 'beyond surface'.
Thanks
05/06/2008 - 16:24
Thanks! That was very clear and helpfull!
08/05/2009 - 16:20
I'll second that! This cleared things up that I hadn't gotten from any other tutorial.
05/19/2008 - 13:40
Thanks for the info. Any way to enable the inserting of data?
05/19/2008 - 15:21
You need to set the property AllowUserToAddRows to true. Any items added to the DataGridView will also be added to the collection bound to it (if you use a collection that supports two-way binding).
06/16/2008 - 03:44
Hello,
what if I've bound a list to the DataGridView in a multi-threaded application. How do I Invoke() in the automatic update of DataGridView in case of adding a new member to the list?
06/16/2008 - 06:46
@Sindik
That is not something I've found a clean solution to yet. At this point, I usually expose a control that can be used for the invoke. Either the actual DataGridView or the application's main form. Then, you'll want to invoke a function that actually adds to the list using the exposed control. That way, the automatic update is also done in the invoked code.
06/25/2008 - 01:01
I have created DataGridView and bind it with DataSource.
When I edit a single cell Value, and alos remain in that row, the dataset didn't get Changes.
07/08/2008 - 05:48
Hi
Supose we have another class called Driver with Name and Age properties. Each car has only 1 driver and the class Car has a Driver property.
How to bind a column to the
Car.Driver.Name property ??
Thanks
01/15/2010 - 10:27
The way I've handled this is to create a view that exposes the nested properties at the level of the view so that they show up in the datagridview. Here's an example:
/// Renders a <see cref="Car"/> into a form suitable for display in the presentation layer.
/// </summary>
public class CarView
{
Car _Car;
public CarView()
{
}
public CarView(Car car)
: this()
{
this._Car = car;
}
public Car Car
{
get { return _Car; }
}
public string DriverName
{
get { return _Car.Driver.Name; }
}
public string Make
{
get { return _Car.Make; }
}
}
public static class CarExtension
{
/// <summary>
/// Derives a <see cref="CarView"/> object from a <see cref="Car"/>.
/// </summary>
/// <param name="source">The <see cref="Car"/> to derive from.</param>
/// <returns>A <see cref="CarView"/> object.</returns>
public static CarView ToView(this Fault source)
{
// Add code to guard for null source
return new CarView(source);
}
}
01/15/2010 - 10:34
Sorry, in the example above, change "Fault" in
public static CarView ToView(this Fault source)to "Car" like
public static CarView ToView(this Car source)07/14/2008 - 08:19
Exactly what I need, thanks a lot !
08/06/2008 - 05:17
Thanks. Just what I was after!
09/15/2008 - 13:45
Thanks! very helpfull for beginners like myself
10/30/2008 - 20:17
How do you select what properties are displayed. In your example all the properties of the "car" were displayed. what if you only wanted model and year for example?
10/30/2008 - 22:02
In my example code, I'm creating a column for each property and assigning it the name of the property I want displayed.
makeColumn.DataPropertyName = "Make";
makeColumn.HeaderText = "The Car's Make";
I make a column for each property, but you don't have to. Just don't add a column for the properties you don't want to see.
12/18/2009 - 10:00
To hide a property just set [Browsable(false)] attribute right over the property
12/18/2009 - 10:01
public int Year
{
get { return _year; }
set
{
_year = value;
this.NotifyPropertyChanged("Year");
}
}
11/05/2008 - 15:59
Where (in what class file) do you put the List?
11/05/2008 - 16:09
It can be anywhere. You could make it a member field, or you could just create it in the constructor (like I did here). I like the member field so you can still access the data after the constructor ends.
11/05/2008 - 16:19
The constructor of the Form class?
11/05/2008 - 17:54
For my example application, yes.
11/06/2008 - 05:16
Its very great example...great explanation...
11/18/2008 - 15:51
Can you comment on the use of BindingSource to bind the List to the Grid? Something like this:
BindingSource1.DataSource = List;
DataGridView1.DataSource = BindingSource1;
11/25/2008 - 07:14
Hi
Thanks for the simple demo. Tried it on a simple new project and it works a treat.
On my existing app however, the datagridview is empty! Any ideas?
Rusty
11/25/2008 - 08:04
Hi
Ignore me. I'm such a numpty! I was trying to bind to a LinkedList. Have changed and is now working fine.
Rusty
12/04/2008 - 17:07
Thank you. This post answered all of the questions I had about updating a dataset. Very useful.
12/23/2008 - 16:17
Thank you very much, great tutorial!
03/18/2009 - 19:36
Has anyone tried a case where the datagrid is bound to a list object as a datasource. However, one of the object's attribute is a list of items, which will vary based on the value of another attribute. In the example above, say, based on the "Car's Make" selected, the "Car's Model" list should be automatically filtered, to show only the Car Models that are applicable for that Make.
04/10/2009 - 08:05
You can autogenerate the columns and rows and still change the name of the columns by using the "DisplayName" attributes
public string Model
{
get { return _model; }
set { _model = value; }
}
04/10/2009 - 10:10
I didn't know that. Thanks for the tip.
04/28/2009 - 14:59
Hi is there a way to link it to an xml file?
05/25/2009 - 09:47
Thanks for the tutorial. Helped me a lot. I am getting some data from the internet and want to show a part of the data in the DataGrid. I have the BindingList and the class. But is it possible that when I add columns, I just add 2 columns while I have 5 properties in the class?
Thanks again.
05/26/2009 - 09:04
Yes. Just create columns for only the properties you want to display. Just make sure AutoGenerateColumns is set to false. Any other properties will simply be ignored by the binding engine.
07/08/2009 - 04:10
A very useful example!
I just have one question :o) When i bind the list to the DataGridView the row for inserting new values disappears. It's possible to display it?
Thanks! ;)
07/28/2009 - 10:46
how will i add items in the column using a textbox.
08/07/2009 - 21:46
Thanks! It was easy to understand!
08/18/2009 - 08:58
Dude, you really know how to write a clear tutorial. Thanks a million.
What makes this a great tutorial is, you start with the simplest most intuitive solution an ordinary person would think of, show how that doesn't quite work, and introduce the next level of complexity. Then show what doesn't quite work with that, and the next more complex solution, and so on.
Infinitely better than the kind of tutorial that says, "You have this object and that object and this other object, and you hook them all together like this...". The reader never has any idea why all those objects exist.
08/31/2009 - 07:31
But I have a problem. I have to display the object as columns, and the propieties as rows. Is some way to do it keeping the binding? I'd love you till the end of time if you could answer this!
09/13/2009 - 21:17
It worked! Great! Thanks!
09/29/2009 - 10:13
Hi!
I've concatenated your tutorials' examples about serialization and this one to make datagrid viewable class that can be serialized. But there's a problem. I don't know how to perform it mostly because of
public event PropertyChangedEventHandler PropertyChanged;field. And there's one more question. When DataGrid is edited, we have our BindingList updated, right? But can I add some other functions that are need to be performed when something's changed in BindingList? Thank you very much in advance.10/12/2009 - 19:05
Great article, exactly what I was looking for. Thanks!
11/20/2009 - 02:10
Thank you, great tutorial! Exactly what I need.
11/22/2009 - 02:17
hi m facing a problem i have a datagrid whose data source is the databse in sql server and it retrieves one column ..i want to add one more column named rating to that same datagrid view named rating...
although i was successful doing that using the columns collection property of the data grid view but how can i add allow user to enter/add values in that newly created column rating and how can i add it to my database there in sql server...
please help...
regards,
vartika
12/26/2009 - 19:26
Looks great, the only issue I have with the binding list is that it doesn't support a sort method. The examples I've seen to implement/create a sort method manually are very convoluted/confusing.
01/28/2010 - 19:09
Fantastic Article!!! Exactly what I seeking! Thanks for sharing your talent!
03/12/2010 - 14:17
Thanks - this is a great tutorial.
In my gridview, one of the columns is a combo box instead of strings or integers. I haven't been able to use this binding method to bind my collection to the gridview. I have tried implementing the property that represents the combo box as both enum and string but it doesn't work - the runtime doesn't like it.
Has anyone else got it to work where one of the columns in the gridview is a combo box?
Thanks in advance.
Add Comment
[language] [/language]
Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]
See here for supported languages.
Javascript must be enabled to submit anonymous comments - or you can login.