In general we use a DataTable
or a DataReader to bind data to a GridView
control, today we shall see on how to bind a C# List to a GridView control.
To know more about the C# List object refer to the post C# List
grdCountry.DataSource = lstCountry;
Related Post
1. C# List
2. Binding a C# List to a DropDownList control
First let us create a class whose
objects will be stored in the List, here is the code for the class.
public class clsCountry
{
public string _CountryCode;
public string _CountryName;
//
public clsCountry(string strCode, string strName)
{
this._CountryCode
= strCode;
this._CountryName
= strName;
}
//
public string CountryCode
{
get {return _CountryCode;}
set {_CountryCode = value;}
}
//
public string CountryName
{
get { return _CountryName; }
set { _CountryName = value; }
}
}
Next, let us create a list of
objects based on our class clsCountry and store them in a List object. Here is the code for the List
List<clsCountry>
lstCountry = new List<clsCountry>();
lstCountry.Add(new clsCountry("USA", "United States"));
lstCountry.Add(new clsCountry("UK", "United Kingdon"));
lstCountry.Add(new clsCountry("IND", "India"));
Finally we shall bind the List object lstCountry to a GridView control. Here the code to bind the
data.
grdCountry.DataSource = lstCountry;
grdCountry.DataBind();
Notice that the columns bound to the GridView control are mapped to the Properties of the class CountryCode and CountryName, hence
make sure to create properties for every member of the class so that they can
be used while binding the data to controls.
That’s it we have bound the
contents of a C# List object
to a GridView control.
1. C# List
2. Binding a C# List to a DropDownList control
1 comment:
The Data Grid Controls for Windows Forms applications are an amazing component for design modern user interface.
Post a Comment