views:

425

answers:

4

Is there an efficient way to overwrite the HTML output of a header and footer of an ASP.NET GridView control?

I would like to implement a methodology that is similar to the HeaderTemplate tag in an ASP.NET Repeater or does not require to include dynamically building the HTML output in the page code behind. If these two types of options are available with a ASP.NET GridView control.

A: 

You may want to consider looking into using an ASP.Net Control Adapter. I have used them for very basic things, but just as Scott Guthrie notes:

A control adapter allows you to plug-into any ASP.NET server control and override, modify and/or tweak the rendering output logic of that control.

The Toolkit also contains several "out of the box" adapters you can draw from for examples, including the GridView. Again, I am not 100% sure you will be able to do exactly what you want, but it is worth checking out for sure. If nothing more than to put another ASP.Net trick under your belt.

Josh
Thanks for the information. I will look into for my next project.
Michael Kniskern
A: 

You can also inherit the control and override the Render function. I had to do that to fix a shortcoming of the ASP.NET radio button. The basic idea is here, you might be able to modify it for your needs:

http://www.codeproject.com/KB/webforms/How_group_RButtons.aspx

ristonj
+1  A: 

In a Gridview, you can use the RowCreated event to completely "destroy" and recreate the header and/or footer. During this event, check to see:

if (e.Row.RowType = DataControlRowType.Header)
{
     // At this point you have access to e.Row.Cells
     // You can now empty the collection and recreate it.
     // If you create a singular cell in the collection
     // you can then make its ColumnSpan reach across
     // the length of the entire table. Then inside this 
     // cell you can add any set of controls you want.
     // I've used this method to combine column headers
     // and add specialty controls that simply wouldn't
     // working using the HeaderTemplate
}

Since this is done at RowCreated, during RowDataBound you would have access to these controls and can then manipulate them however you like based on data. This is handy for doing complicated calculations in the footer, adjusting images in the header based on sort, etc.

Joel Etherton
A: 

To change cell-by-cell checking on RowCreated is the way to do it e.g. if you wanted to add a drop-down to a column to allow filtering you could do.

if (e.Row.RowType = DataControlRowType.Header)
{
    e.Row.Cells[0].Controls.Clear();

    var ddlFilter = new DropDownList();
    //add options etc

    e.Row.Cells[0].Controls.Add(ddlFilter);
}

If you were going to convert to a single cell and add new controls then I would just set ShowHeader=false and put my markup/controls above the gridview

Adam Pope