Monday, May 17, 2010

Binding a Generic List to ASP.Net GridView

when working with ASP.Net GridView it has many options as its data source one such important option is List. most of the time we use Generic Lists as the data source. Binding a Generic List is not that difficult.

Suppose that you are binding a Generic List which has Objects with properties
  • id
  • email
  • tp
  • purchase
  • sales
  • returns
  • purchaseReturns
in the asp web page add a GridView and using the designer or source add bound fields (using bound field is very easy but you use other field if necessary). Then set the Data Field property of the bound fields to the matchi property of the data object. Then source will look something like this.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField HeaderText="Id" DataField = "id">
</asp:BoundField>
<asp:BoundField HeaderText="email" DataField = "email">
</asp:BoundField>
<asp:BoundField HeaderText="tp" DataField = "tp">
</asp:BoundField>
<asp:BoundField HeaderText="purchase" DataField = "purchase">
</asp:BoundField>
<asp:BoundField HeaderText="return" DataField="purchaseReturns">
</asp:BoundField>
<asp:BoundField HeaderText="sales" DataField = "sales">
</asp:BoundField>
<asp:BoundField HeaderText="return" DataField = "returns">
</asp:BoundField>
</Columns>
</asp:GridView>







Then you have to bind the data source to the GridView in the .cs file you may use the page load method for it.

first you should create a Generic List of the Object type you want to Bind. you cannot see the GridView in Run time unless you bind even an empty data source to it.

GridView1.DataSource = testlist; //bind the List to the GridView
GridView1.DataBind();

above code will bind the Generic list to the GridView.

Important:
When you are creating the class that you are using to create the Generic List you should create Getters for all the attributes that you are binding to the GridView else you will see an error message attribute (data field) not exist in the data source.

1 comment: