How to present data in DataGridView with objects collection in C#
Some times we can't just bind data source to a datagridview as we need much deeper data to be presented in our grid. In such a situation we can use the following method to get it done.
1) Prepare your Grid with columns as usual
2) Let say our datasource consists this structure
Classes are like this
I need to show the bowler's first name, last name, nic, and the bowling style in the grid (I've already created the columns for that)
//dataGridView1.DataSource = bowlers; // if you use this binding you can't display the inner data of players style in the grid. So I use
You have to be careful to match the exact columns with the bowler fields when you lay them in the Add method.
1) Prepare your Grid with columns as usual
2) Let say our datasource consists this structure
Classes are like this
1: public class Player
2: {
3: public int ID{get;set;}
4: public string FirstName{get;set;}
5: public string LastName{get;set;}
6: public string FullName
7: {
8: get { return FirstName + " " + LastName; }
9: }
10: public int Age{get;set;}
11: public string NIC{get;set;}
12: public Style PStyle{get;set;} // associated Style property
13: }
14: public class Style
15: {
16: public int StyleID{get;set;}
17: public string Name{get;set;}
18: }
Using Player class I need to get a list of Players to the grid
1: List bowlers = DataAccess.GetBowlers();
I need to show the bowler's first name, last name, nic, and the bowling style in the grid (I've already created the columns for that)
//dataGridView1.DataSource = bowlers; // if you use this binding you can't display the inner data of players style in the grid. So I use
1: foreach (Player bowler in bowlers)
2: {
3: dataGridView1.Rows.Add(new object[] { bowler.FirstName + " " + bowler.LastName, bowler.NIC, bowler.Style.Name });
4: }
Comments