Search This Blog

Monday, January 10, 2011

Gridview column width when AutoGenerateColumns=true

There are occasions when one may work with a data source that provides dynamic columns. A stored procedure that aggregates year-to-date totals, with columns representing the months-to-date, is an example. Towards the beginning of the year, there are only a few columns of data; towards the end of the year, there are many. When displaying data like this in a DataGrid or a GridView control, it is convenient to set AutoGenerateColumns=true, letting ASP.NET create the necessary display columns at runtime. Unfortunately, columns generated this way are not available to the developer through the grid’s Columns property, and thus the developer lacks the ability to establish column-based formatting.


In the aspx page add this style



<style type="text/css">
.wordwrap
{
    word-break:break-all;
    word-wrap:break-word;
    overflow:hidden;
    width:150px;
}
.sno
{
    word-break:break-all;
    word-wrap:break-word;
    overflow:hidden;
    width:50px;
}
</style>




And in the code behind use this code in the RowDataBound Event of the Gridview
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.Cells.Count > 0)
        {
            for (int i = 1; i > e.Row.Cells.Count; i++)
            {
                e.Row.Cells[i].CssClass = "wordwrap";               
            }
        }
        e.Row.Cells[0].CssClass = "sno";
    } 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.