Click here to Skip to main content
15,867,939 members
Articles / Web Development / XHTML

GridView Enhancements and Fixes

Rate me:
Please Sign up or sign in to vote.
4.92/5 (22 votes)
12 Feb 2009CPOL6 min read 72.9K   373   53   22
Enhancements and fixes that add features: more control over column widths, preventing text wrapping, formatting auto-generated columns.

Introduction

Have you ever needed to control the widths of your columns in a GridView especially when the GridView's width is relative to the container (for example: width="100%") and the columns keep getting the total width of the GridView distributed among them? All you want is for each column to take just enough width to display its contents and the remaining width can be allocated to the last column, but that did not work, did it? Have you ever tried using the Wrap="False" in a GridView's RowStyle or HeaderStyle and were surprised it did not work in all browsers? This article is my take at solving these two issues, and it works in both IE and FF.

In addition, I present a method to solve a problem when using automatically generated columns in the GridView. As is known, there is a property of the GridView: AutoGenerateColumns, that when set to true would generate the columns automatically from the DataSource. The problem is that we have limited control (if any) on those generated columns. So for example, if the DataSource contains a Date column, the displayed data would not show as formatted, showing for example (1/1/2008 12:00:00 AM) instead of just (1/1/2008) or (01/01/2008), etc... That is a problem because we cannot (directly) change the formatting to meet our requirements. The best way to solve this would be to inherit from GridView and customize the GridView to our liking. For those (like me) that don't want to deal with another extra reference in their project, I have another way.

Background

My solution depends on JavaScript and DOM. I am using Element Injection into the existing HTML. The code is not that complex, and you don't need to be scared by these intimidating terms. You would need though to know a bit of JavaScript and what DOM (Document Object Model) actually means. If you find you lack such knowledge, a few minutes with Google will save you.

For the auto-generated columns problem, my solution depends on Reflection to set values of members that don't have public accessibility. Reflection has a performance penalty that at situations can be afforded. If you find that my solution has weak performance (which I did not notice, neither did I test for), then try the alternative: Inheritance.

Illustration

Following are a few images that illustrate what my solution does:

This is what the sample code would look like without my solution:

NoneFixed.jpg

This is how it looks like with columns formatted, and wrapping not changed:

WrappingNotFixed.jpg

This is how it looks like with columns formatted and wrapping fixed for the header:

WrappingFixedHeader.jpg

This is when all features are enabled (wrapping fixed for both the header and data rows):

AllFixed.jpg

This is how Date fields appear without formatting:

AutoGenColsNoFormatting.jpg

This is how Date fields appear after formatting is applied:

AutoGenColsWithFormatting.jpg

Column Widths and Wrapping

ColumnWidthsAndWrapping.aspx

There are two parts to the solution: the JavaScript which resides in the ASPX page, and the code that registers calls to those functions, which resides in the code-behind of that page.

Let us start with the JavaScript functions:

JavaScript
function formatGrid(el)
{
    el = document.getElementById(el);               
    var numOfCols = 
      el.getElementsByTagName("TR")[1].getElementsByTagName("TD").length;                
    var colGrp = document.createElement("colgroup");                
    var col = document.createElement("col");
    col.setAttribute("span", numOfCols-1);
    col.setAttribute("width", "1");
    col.setAttribute("white-space", "nowrap");
    col.setAttribute("padding-left", "2");
    col.setAttribute("padding-right", "2");
    col.setAttribute("border-width", "2");
    colGrp.appendChild(col);                
    el.insertBefore(colGrp, el.firstChild);                
}

The function formatGrid receives the ID of an element in the document, which in our case would normally be the GridView. What this function does is format the GridView so that each column gets just enough width to display its contents and the last column gets all the remaining width. Remember, we are usually dealing here with a GridView that has a width of 100%. The code is relatively clear, I will just point out the following:

  1. We are getting the number of columns in the GridView, numOfCols, and using numOfCols - 1 later.
  2. The ColGroup element is responsible for grouping columns and assigning them common properties.
  3. The Col element is a child of the ColGroup element and will override what is set on the ColGroup element, and that is why it is sufficient to set attributes on the Col element (I am using simple terms, for more info: check http://www.w3.org/TR/html401/struct/tables.html#h-11.2.4.1).
  4. The span<code> attribute indicates how many columns the Col element will affect; in our case, we need to restrict the width of all the columns except the last one.
  5. The only required attributes are the span and the width attributes, the others are optional.

The following functions solve the wrapping part of the problem, where we would need something like "First Name" in the header of the GridView to appear on the same line and not wrap and split over two lines. Also, this applies to the data rows where the data can be long, and thus be forced to wrap to another line thus being split across two or more lines. We might need them to appear as a unit on one line. Now, using the following functions, it is easier:

JavaScript
function addNoWrapSpan(el, noWrap)
{
    var span = document.createElement("span");
    while(el.childNodes.length > 0)
    {
        var child = el.firstChild;
        el.removeChild(child);
        span.appendChild(child);
    }                
    if(noWrap)
    span.style.whiteSpace = "nowrap";
    else
    span.style.whiteSpace = "inherit";
    el.appendChild(span);
}
function setNoWrap(el, noWrapTH, noWrapTD)
{
    el = document.getElementById(el);
    if(noWrapTH)
    {
        var allTHs = el.getElementsByTagName("TH");                
        for(var i = 0; i < allTHs.length; i++)
        {
            addNoWrapSpan(allTHs[i], noWrapTH);
        }
    }
    if(noWrapTD)
    {
        var allTDs = el.getElementsByTagName("TD");                
        for(var i = 0; i < allTDs.length; i++)
        {
            addNoWrapSpan(allTDs[i], noWrapTD);
        }
    }
}

The first function addNoWrapSpan moves all the elements inside the provided element el (be it a td or th) to a dynamically generated span element that has the proper style depending on whether noWrap is true or false. The style used is:

JavaScript
span.style.whiteSpace = "nowrap"; 

if noWrap is true and if it is false, then the following style is set:

JavaScript
span.style.whiteSpace = "inherit";

setNoWrap receives three parameters: el which is the element that we are configuring, noWrapTH that tells us whether or not to allow wrapping for the child THs, and noWrapTD indicating whether or not to allow wrapping on the TDs inside the element el. As you can notice, setNoWrap calls addNoWrapSpan where necessary.

The attached sample project includes a sample GridView:

ASP.NET
<asp:GridView ID="GridView1" runat="server" 
          AutoGenerateColumns="False" Width="100%" 
          CssClass="GridClass">
    <Columns>
        <asp:BoundField DataField="FirstName" HeaderText="First Name" />
        <asp:BoundField DataField="LastName" HeaderText="Last Name" />               
        <asp:BoundField DataField="Age" HeaderText="Age" />
        <asp:CommandField ShowSelectButton="True" />
    </Columns>
</asp:GridView>

Simply, it displays the data set in the code-behind and also has a CommandField which has a select LinkButton. Now, the code-behind:

C#
private DataTable BuildDataSource()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("FirstName", typeof(string));
    dt.Columns.Add("LastName", typeof(string));
    dt.Columns.Add("Age", typeof(int));
    
    DataRow dr;
    
    dr = dt.NewRow();
    dr["FirstName"] = "John the first";
    dr["LastName"] = "Doe";
    dr["Age"] = 23;
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr["FirstName"] = "Clark";
    dr["LastName"] = "Kent";
    dr["Age"] = 28;
    dt.Rows.Add(dr);

    return dt;
}

This is a simple way to show data for test purposes; this will be replaced by code to retrieve data from the database in real case scenarios:

C#
protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);
    string formatScript = "";
    formatScript += string.Format("formatGrid('{0}');" + 
                    "setNoWrap('{0}', false, true);", 
                    GridView1.ClientID);        
    ClientScript.RegisterStartupScript
        (this.GetType(), "format", formatScript, true);
}

This is where our JavaScript is put to use. Notice that I am calling setNoWrap and assigning false for the noWrapTH parameter; this means that the header will still wrap if its contents are long, you probably will need to change that to true.

Automatically Generated Columns

AutoGeneratedColumns.aspx

Here I describe a method that allows us to format dates inside automatically generated columns (AutoGenerateColumns =true).

C#
private void FormatDatesInGridView(GridView gv, GridViewRow gvr)
{
    if (gv.DataSource != null)
    {
        DataTable dt = null;

        if (gv.DataSource is DataView)
        {
            dt = ((DataView)gv.DataSource).Table;
        }
        else
            if (gv.DataSource is DataSet)
            {
                dt = ((DataSet)gv.DataSource).Tables[0];
            }
            else
                if (gv.DataSource is DataTable)
                {
                    dt = (DataTable)gv.DataSource;
                }

        if (gvr.RowType == DataControlRowType.DataRow)
        {
            foreach (TableCell tc in gvr.Cells)
            {
                DataControlFieldCell dcfc = (DataControlFieldCell)tc;
                if (dcfc.ContainingField is AutoGeneratedField)
                {
                    AutoGeneratedField agf = (AutoGeneratedField)dcfc.ContainingField;
                    if (agf.DataType == typeof(DateTime))
                    {
                        System.Reflection.FieldInfo fi;
                        fi = typeof(BoundField).GetField("_dataFormatString", 
                             System.Reflection.BindingFlags.Instance | 
                             System.Reflection.BindingFlags.NonPublic);
                        fi.SetValue(agf, "{0:dd/MM/yyyy}");

                        fi = typeof(DataControlField).GetField("_statebag", 
                             System.Reflection.BindingFlags.Instance | 
                             System.Reflection.BindingFlags.NonPublic);
                        ((StateBag)fi.GetValue(agf))["DataFormatString"] = 
                                              "{0:dd/MM/yyyy}";

                        System.Reflection.MethodInfo mi;
                        mi = typeof(BoundField).GetMethod("OnFieldChanged", 
                             System.Reflection.BindingFlags.NonPublic | 
                             System.Reflection.BindingFlags.Instance);
                        mi.Invoke(agf, null);
                        ((BoundField)agf).HtmlEncode = false; //Fix for Dates Formatting
                    }
                }
            }
        }
    }
}

The method called FormatDatesInGridView is to be called from inside the RowCreated event handler of the GridView to be formatted. This method receives two parameters: the GridView and the current row. The calling event handler would look like:

C#
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
        FormatDatesInGridView(GridView1, e.Row);
}

The method first determines the DataSource of the GridView (could be modified if you have other types as DataSource). Then, it checks all cells of the current GridViewRow, and if the type of the ContainingField of the AutoGeneratedField is DateTime, we do the following using Reflection:

  • set _dataFormatString to "{0:dd/MM/yyyy}" (could be changed to meet requirements).
  • set Viewstate["DataFormatString"] to the same value "{0:dd/MM/yyyy}" by setting the value of _statebag["DataFormatString"].
  • call the OnFieldChanged method to apply these changes (this method eventually causes Binding to occur).
  • Update: apparently, HtmlEncode is sometimes true in some environments, which prevents us from controlling the formatting of the dates. That is why I added the line to set it to false.

That's it, the date fields are now formatted. How I came up with these steps is by using Reflector and checking how the classes work internally.

Update History

  • 12 February 2009: HtmlEncode fix for date formatting.
  • 03 August 2008: Auto-generated columns.
  • 22 June 2008: Added the Illustration section.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Lebanon Lebanon
Over 5 years of experience as a Web Developer using ASP.NET.
Appreciates Good Design and continually seeks to improve his methods.

MCP in Developing Web Applications using ASP.NET, and in XML Web Services and Server Components.

Comments and Discussions

 
GeneralDoes not work with GridView paging Pin
dreames6-Nov-09 3:56
dreames6-Nov-09 3:56 
GeneralRe: Does not work with GridView paging Pin
M. Shehabeddeen6-Nov-09 6:10
M. Shehabeddeen6-Nov-09 6:10 
GeneralSuggestion Pin
SmirkinGherkin12-Feb-09 4:13
SmirkinGherkin12-Feb-09 4:13 
GeneralRe: Suggestion Pin
M. Shehabeddeen12-Feb-09 4:29
M. Shehabeddeen12-Feb-09 4:29 
GeneralRe: Suggestion Pin
SmirkinGherkin12-Feb-09 5:10
SmirkinGherkin12-Feb-09 5:10 
GeneralRe: Suggestion Pin
M. Shehabeddeen12-Feb-09 6:07
M. Shehabeddeen12-Feb-09 6:07 
GeneralRe: Suggestion Pin
SmirkinGherkin12-Feb-09 21:01
SmirkinGherkin12-Feb-09 21:01 
QuestionHTML Encode missing? Pin
wizake12-Feb-09 0:30
wizake12-Feb-09 0:30 
AnswerRe: HTML Encode missing? Pin
M. Shehabeddeen12-Feb-09 1:18
M. Shehabeddeen12-Feb-09 1:18 
Generalin the content page Pin
yan194543-Dec-08 4:21
yan194543-Dec-08 4:21 
GeneralGood approach Pin
Adam Tibi6-Aug-08 0:15
professionalAdam Tibi6-Aug-08 0:15 
GeneralRe: Good approach Pin
M. Shehabeddeen6-Aug-08 2:12
M. Shehabeddeen6-Aug-08 2:12 
QuestionWhy JavaScript? Pin
existenz_4-Aug-08 22:40
existenz_4-Aug-08 22:40 
AnswerRe: Why JavaScript? Pin
M. Shehabeddeen4-Aug-08 23:06
M. Shehabeddeen4-Aug-08 23:06 
GeneralRe: Why JavaScript? Pin
existenz_5-Aug-08 1:54
existenz_5-Aug-08 1:54 
GeneralNice Article Pin
Mehdi Payervand4-Aug-08 0:46
Mehdi Payervand4-Aug-08 0:46 
Generaluseful tips. Pin
Rajib Ahmed24-Jun-08 10:25
Rajib Ahmed24-Jun-08 10:25 
GeneralGreat job, useful for me! Pin
guaike22-Jun-08 3:23
guaike22-Jun-08 3:23 
GeneralGood One! Pin
indyfromoz20-Jun-08 9:15
indyfromoz20-Jun-08 9:15 
GeneralRe: Good One! Pin
M. Shehabeddeen21-Jun-08 8:53
M. Shehabeddeen21-Jun-08 8:53 
GeneralThanks Man Pin
mohamadabdou17-Jun-08 2:53
mohamadabdou17-Jun-08 2:53 
GeneralRe: Thanks Man Pin
M. Shehabeddeen17-Jun-08 3:01
M. Shehabeddeen17-Jun-08 3:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.