Wednesday, October 3, 2007

Creating subheader in gridview


<asp:gridview id="GridView1" class="attr"> runat="server" autogeneratecolumns= class="attrv">"false" datasourceid="SqlDataSource1"
onrowdatabound="GridView1_RowDataBound">
<columns>
<asp:boundfield datafield= class="attrv">"ProductID" headertext="ProductID" />
<asp:boundfield datafield= class="attrv">"Name" headertext="Name" />
<asp:boundfield datafield= class="attrv">"Subcategory" headertext="Subcategory" />
</columns>
</asp:gridview>
<asp:sqldatasource id= class="attrv">"SqlDataSource1" runat="server" class="attr"> connectionstring="<%$
ConnectionStrings:AdventureWorksConnectionString %>"

selectcommand="SELECT P.*, PS.[Name]
AS [Subcategory] FROM [Production].[Product] AS P INNER JOIN [Production].[ProductSubcategory]
AS PS ON PS.[ProductSubcategoryID] = P.[ProductSubcategoryID] ORDER BY P.[ReorderPoint],
P.[Name]"
>
</asp:sqldatasource>


CODE-BEHIND 



private string m_subcategory = String.Empty;

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

switch (gvr.RowType)
{
case DataControlRowType.DataRow:
{
DataRowView drv = gvr.DataItem as DataRowView;

string subcategory = drv["subcategory"].ToString();

if (!subcategory.Equals(m_subcategory))
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
TableCell cell = new TableCell();
cell.BackColor = Color.Red;
cell.ForeColor = Color.White;
cell.ColumnSpan = GridView1.Columns.Count;
cell.HorizontalAlign = HorizontalAlign.Center;
cell.Text = subcategory;
row.Cells.Add(cell);

GridView1.Controls[0].Controls.AddAt(GridView1.Controls[0].Controls.Count - 1, row);

m_subcategory = subcategory;
}


break;
}
}
}

3 comments:

Anonymous said...

works (and looks) wonderful on the initial post to the screen, if you do a post back all databound values are missing?

Anonymous said...

Thanks, Works well, but some of the links in the gridview are not working.
i.e. last n number of records,
where n is the number of subheaders.

plefrancois said...

Hi , thanks for your code, very useful for me. How to add the number of categories on each respective line. EX:
Category1 = 4, Category1 = 3, etc.
Thank you for taking the time to answer me, it would be greatly useful for me.