How to populate asp:GridView from code?

Boris picture Boris · Oct 18, 2012 · Viewed 29.3k times · Source

I have a List<string[]> items list filled with arrays of strings in my code. On the ASPX page, I have added a new grid view control:

<asp:GridView ID="ProductList" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ProductID" EnableViewState="False">
  <Columns>
    <asp:BoundField DataField="ProductName" HeaderText="Product" SortExpression="ProductName" />
    <asp:BoundField DataField="CategoryName" HeaderText="Category" ReadOnly="True" SortExpression="CategoryName" />
    <asp:BoundField DataField="SupplierName" HeaderText="Supplier" ReadOnly="True" SortExpression="SupplierName" />
    <asp:BoundField DataField="UnitPrice" DataFormatString="{0:C}" HeaderText="Price" HtmlEncode="False" SortExpression="UnitPrice" />
    <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" SortExpression="Discontinued" />
  </Columns>
</asp:GridView>

I know that I should specify the DataSourceID attribute for the grid view in a fashion similar to this:

<asp:GridView ... `DataSourceID="ObjectDataSource1" ... > 
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetProducts" TypeName="ProductsBLL">
</asp:ObjectDataSource>

But, I don't know what do OldValuesParameterFormatString, SelectMethod and TypeName attributes represent. Also, I don't have the database to bind to, I just have the list of string arrays named items. Can you help me populate the grid view? It is not necessary to do it through the binding at all. Thanks!

Answer

danyim picture danyim · Oct 18, 2012

You don't even need an ObjectDataSource. At Page_Load in the codebehind, you can parse through the string array list and create a DataTable on the fly.

Make sure to wrap this around a Not Page.IsPostback so that it doesn't rebind on postback.

List<string[]> stringList = null;

DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add("ProductName", System.Type.GetType("System.String"));
dt.Columns.Add("CategoryName", System.Type.GetType("System.String"));
dt.Columns.Add("SupplierName", System.Type.GetType("System.String"));
dt.Columns.Add("UnitPrice", System.Type.GetType("System.Double"));
dt.Columns.Add("Discontinued", System.Type.GetType("System.String"));

foreach (string[] s in stringList) {
    foreach (string str in s) {
        dr = dt.NewRow();
        dr["ProductName"] = s[0];
        dr["CategoryName"] = s[1];
        dr["SupplierName"] = s[2];
        dr["UnitPrice"] = s[3];
        dr["Discontinued"] = s[4];
        dt.Rows.Add(dr);
    }
}

dt.AcceptChanges();
ProductList.DataSource = dt;
ProductList.DataBind();