Share via


How to: Set GridView Web Server Control Column Width Dynamically

By default, columns in the GridView control are sized automatically. Columns render as HTML table cells (td elements) without width information; most browsers size table cells to allow for the widest content in the column.

If it is required, you can set the width of individual columns in the GridView control programmatically. This is useful, if the width of the column depends on information that is available only at run time. For example, you might size a column according to its contents—that is, based on the data that the GridView control binds to.

The basic technique for setting column width involves setting the Width property of a column template. If you want the width to be set according to its contents, you can handle the RowDataBound event. This makes the data for a row available to you for examination.

To set column width dynamically

  • In code, set the Width property of the ItemStyle property for a GridView control column to the width that you want.

    The following code example shows how to set the width of all the columns in the GridView1 control to the value that a user enters in a text box. Error messages are displayed in a Label control.

    Protected Sub TextBox1_TextChanged (ByVal sender As Object, _
            ByVal e As System.EventArgs)        Label1.Text = ""
        Try
          Dim colWidth As Integer
          colWidth = CInt(Server.HtmlEncode(TextBox1.Text))
          If colWidth > 0 Then
            For i As Integer = 0 To GridView1.Columns.Count - 1
              GridView1.Columns(i).ItemStyle.Width = colWidth
            Next
          End If
        Catch
          Label1.Text = "An error occurred."
        End Try
    End Sub
    
    protected void TextBox1_TextChanged (object sender, EventArgs e)
    {    Label1.Text = "";
        try
        {
          int colWidth = Int16.Parse(Server.HtmlEncode(TextBox1.Text));
          if (colWidth > 0)
          {
            for (int i = 0; i < GridView1.Columns.Count; i++)
            {
              GridView1.Columns[i].ItemStyle.Width = colWidth;
            }
          }
        }
        catch
        {
          Label1.Text = "An error occurred."
        }
    }
    

To set column width based on data contents

  1. Create a handler for the RowDataBound event.

    The RowDataBound event is raised each time that a new row is data-bound in the grid and gives you access to the data for each row.

  2. In the event handler, do the following:

    1. Create a DataRowView object and assign to it the DataItem value for the current grid row.

      The DataItem property is typed as an object. Therefore, you must cast it.

    2. Test for a data row (DataControlRowType) to make sure that you are working with a data-bound row and not a header or footer.

    3. From the DataRowView object, extract the data value that you want to examine.

    4. Set the Width property for the ItemStyle property.

    5. Set the Wrap property of the ItemStyle property to false.

      If the Wrap property is false, the column is automatically resized.

    The following code example shows how to set the width of a column (in this case, the third column) based on the width of the widest data element of the second column. The RowDataBound event handler is called one time for each data row that is displayed by the GridView control. The code stores the character count of the widest element in a protected page member. The code sets the width of the column to the character count times 30 (an arbitrary multiplier).

    Protected widestData As Integer
    Protected Sub GridView1_RowDataBound(ByVal sender As Object, _
            ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
        Dim drv As System.Data.DataRowView
        drv = CType(e.Row.DataItem, System.Data.DataRowView)
        If e.Row.RowType = DataControlRowType.DataRow Then
          If drv IsNot Nothing Then
            Dim catName As String = drv(1).ToString()
            Dim catNameLen As Integer = catName.Length
            If catNameLen > widestData Then
              widestData = catNameLen
              GridView1.Columns(2).ItemStyle.Width = _
                  widestData * 30
              GridView1.Columns(2).ItemStyle.Wrap = False
            End If
          End If
        End If
    End Sub
    
    Protected Sub Page_Load(ByVal sender As Object, _
            ByVal e As System.EventArgs) Handles Me.Load
        widestData = 0
    End Sub
    
    protected int widestData;
    protected void GridView1_RowDataBound(object sender, 
        GridViewRowEventArgs e)
    {
        System.Data.DataRowView drv;
        drv = (System.Data.DataRowView)e.Row.DataItem;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
          if (drv != null)
          {
            String catName = drv[1].ToString();
            Response.Write(catName + "/");
    
            int catNameLen = catName.Length;
            if (catNameLen > widestData)
            {
              widestData = catNameLen;
              GridView1.Columns[2].ItemStyle.Width =
                widestData * 30;
              GridView1.Columns[2].ItemStyle.Wrap = false;
            }
    
          }
        }
    }
    
    protected void Page_Load(object sender, EventArgs e)
    {
        widestData = 0;
    }
    

See Also

Reference

GridView Web Server Control Overview