Merging Gridview Columns or adding Controls to Gridview row:

Merging Gridview Columns or adding Controls to Gridview row:

Header Columns of Gridview are merged by using RowCreated Event of GridView.

Before the GridView control can be rendered, a GridViewRow object must be created for each row in the control.

The RowCreated event is raised when each row in the GridView control is created. This enables you to provide an event-handling method that performs a custom routine, such as adding custom content to a row, whenever this event occurs.

protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow HeaderGridRow = new GridViewRow(0,1, DataControlRowType.Header, DataControlRowState.Normal);
//GridViewRow HeaderGridRow = new GridViewRow(RowIndex,DataItemIndex,RowType,RowState)
//Row Index – Gets the index of the GridViewRow object in the Rows collection of a GridView control.
//DataItemIndex – Gets the index of the DataItem in the underlying DataSet.
//RowType – Gets the row type of the GridViewRow object.
//RowState – Gets the state of the GridViewRow object.

//Creating Cell
TableCell HeaderCell = new TableCell();
//Header Text
HeaderCell.Text = “”;

//if you want to add a control to HeaderCell
//TextBox abc = new TextBox();
// HeaderCell.Controls.Add(abc);

//No of cell to merge in below row
HeaderCell.ColumnSpan = 1;
//Adding cells to header
HeaderGridRow.Cells.Add(HeaderCell);

HeaderCell = new TableCell();
HeaderCell.Text = “Q1 (Apr-Jun)”;
HeaderCell.HorizontalAlign = HorizontalAlign.Center;
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderCell = new TableCell();
HeaderCell.Text = “Q2 (Jul-Sep)”;
HeaderCell.HorizontalAlign = HorizontalAlign.Center;
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderCell = new TableCell();
HeaderCell.Text = “Q3 (Oct-Dec)”;
HeaderCell.HorizontalAlign = HorizontalAlign.Center;
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderCell = new TableCell();
HeaderCell.Text = “Q4 (Jan-Mar)”;
HeaderCell.HorizontalAlign = HorizontalAlign.Center;
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderCell = new TableCell();
HeaderCell.Text = “Total”;
HeaderCell.HorizontalAlign = HorizontalAlign.Center;
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

//Adding Row to Gridview
GridView3.Controls[0].Controls.AddAt(0, HeaderGridRow);
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s