How To Create Bound Column Dynamically (Data Grid)

Step 1

Add the GridView to your page.

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <title>Untitled Page</title>
    <form id="form1" runat="server">
            <asp:DataGrid ID="datagrid1" runat="server" AutoGenerateColumns="false" OnDataBinding="DataGrid1_DataBinding"
       <asp:Label ID="lblStatus" runat="server"></asp:Label> 


Create DataTable

private DataTable CreateTable()
        DataTable ret = new DataTable();
        ret.Columns.Add(new DataColumn("ID", typeof(int)));
        ret.Columns.Add(new DataColumn("Column1", typeof(Int32)));
        ret.Columns.Add(new DataColumn("Column2", typeof(Int32)));
        //Make some rows and put some sample data in
        DataRow dr;
        int i;
        for (i = 1; i <= 10; i++)
            dr = ret.NewRow();
            dr[0] = i;
            dr[1] = i * 25;
            dr[2] = i * i;
            //add the row to the datatable
        return ret;

Step 3

Bind GridView (notice that for dynamically created controls within the datagrid to fire up the
itemcommand event, the datagrid needs to be created during the initialization stage
of the page’s lifecycle)

protected void Page_Init(object sender, System.EventArgs e)
        datagrid1.DataSource = CreateTable();

Step 4

Now we will loop through the columns on the datatable and build a tempalte column that has one imagebutton in it
add it to the grid.columns collection then create another boundcolumn that would display the value in the column

protected void DataGrid1_DataBinding(object sender, EventArgs e)
         tbl = CreateTable();
        foreach (DataColumn dc in tbl.Columns)
            TemplateColumn tc = new TemplateColumn();
            tc.ItemTemplate = new MyTemplate(ListItemType.Item, dc.ColumnName);

            BoundColumn bc = new BoundColumn();
            //add a column to contain the value of the field
            bc.DataField = dc.ColumnName;
            bc.DataFormatString = "{0:C}";
            bc.HeaderText = dc.ColumnName;


protected void DataGrid1_ItemCommand(object sender, DataGridCommandEventArgs e)
      //I saved the ImageButton ID in the CommandAgument to be able to search by it
      ImageButton btnImage = e.Item.FindControl(e.CommandArgument.ToString()) as ImageButton;
      //toggle the image
      if (btnImage.ImageUrl == "images/left.gif")
          btnImage.ImageUrl = "images/right.gif";
          btnImage.ImageUrl = "images/left.gif";
      lblStatus.Text = "commandName = " + e.CommandName + "  at row = " + e.Item.ItemIndex + "
button image = " + btnImage.ImageUrl;
Next Post Previous Post
No Comment
Add Comment
comment url