Thursday, July 30, 2009

merge the header row for the GridView control

some time we want to merge the Gridview Content as well as the Header also ,it was very easy in html you need to simply add the Colspan attribute and with the help of that you can set is (2, 3 )what ever you want.

Here is the way you can do that same thing in C#


<asp:gridview id="GridView1" runat="server" allowpaging="True" autogeneratecolumns="False"
datakeynames="ProductID" datasourceid="SqlDataSource1" onrowdatabound="GridView1_RowDataBound">
<columns>
<asp:boundfield datafield="ProductID" headertext="ProductID" insertvisible="False"
readonly="True" sortexpression="ProductID" />
<asp:boundfield datafield="ProductName" headertext="ProductName" sortexpression="ProductName" />
<asp:boundfield datafield="CategoryID" headertext="CategoryID" sortexpression="CategoryID" />
<asp:boundfield datafield="CategoryName" headertext="CategoryName" sortexpression="CategoryName" />
</columns>
</asp:gridview>
<asp:sqldatasource id="SqlDataSource1" runat="server" connectionstring="<%$ ConnectionStrings:NorthwindConnectionString %>"
selectcommand="SELECT [ProductID], [ProductName], [CategoryID], [CategoryName] FROM Product_Details">
</asp:sqldatasource>




and here is CODEBEHIND Source



protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow gvr = e.Row;

if (gvr.RowType == DataControlRowType.Header)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);

TableCell cell = new TableCell();
cell.ColumnSpan = 2;
cell.HorizontalAlign = HorizontalAlign.Center;
cell.Text = "Product";
row.Cells.Add(cell);

cell = new TableCell();
cell.ColumnSpan = 2;
cell.HorizontalAlign = HorizontalAlign.Center;
cell.Text = "Category";
row.Cells.Add(cell);

GridView1.Controls[0].Controls.AddAt(0, row);
}
}

No comments:

Post a Comment