Adsence750x90

Friday, May 28, 2010

Add GridView Column Dynamically ASP.Net and C #

Add GridView Column Dynamically 
This code illustrate how to add a new Column in GridView on GridView1_RowCreated and add column value in GridView1_RowDataBound
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class dhilip : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
        //instance of a datatable
        DataTable dt = new DataTable();
        //instance of a datarow
        DataRow drow;
        //creating two datacolums Column1 and Column2 
        DataColumn dcol1 = new DataColumn("Column1", typeof(string));
        DataColumn dcol2 = new DataColumn("Column2", typeof(string));
        //adding datacolumn to datatable
        dt.Columns.Add(dcol1);
        dt.Columns.Add(dcol2);
        //loop for 10 rows
        for (int i = 0; i < 10; i++)
        {
            //instance of a datarow
            drow = dt.NewRow();
            //add rows to datatable
            dt.Rows.Add(drow);
            //add Column values
            dt.Rows[i][dcol1] = i.ToString();
            dt.Rows[i][dcol2] = i.ToString();
        }
        //set gridView Datasource as dataTable dt.
        GridView1.DataSource = dt;
        //Bind Datasource to gridview
        GridView1.DataBind();
    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //create a instance of table cell
        // this table cell is going to add gridview as new column
        TableCell tc = new TableCell();
        //first cell must be -1 ie the header of gridview. if it header
        if (e.Row.RowIndex == -1)
        {
            //add header column name. you can add more styles in this section
            tc.Text = "Multiple";
            //add style for header column
            tc.Style.Add(HtmlTextWriterStyle.FontWeight, "bold");
        }
        //cell add to gridview row
        e.Row.Cells.Add(tc);
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //if header column we dont need multiplication
        if (e.Row.RowIndex != -1)
        {
            //taking values from first cell. my first cell contain value, you can change
            string id = e.Row.Cells[0].Text;
            //taking values from second cell. my second cell contain value, you can change
            string id2 = e.Row.Cells[1].Text;
            //multiplication
            double mult = int.Parse(id) * int.Parse(id2);
            //adding result to last column. coz we add new column in last.
            e.Row.Cells[e.Row.Cells.Count - 1].Text = mult.ToString();
        }
    }
}