Click here to Skip to main content
13,355,311 members (63,983 online)
Click here to Skip to main content
Add your own
alternative version


9 bookmarked
Posted 19 Dec 2011

Set Width of gridview columns dynamically when AutoGenerateColumns=“true”

, 21 Dec 2011
Rate this:
Please Sign up or sign in to vote.
Set Width of gridview columns dynamically when AutoGenerateColumns=“true”


I faced a lot of problems when I asked to set the width of a gridview dynamically, that is the property AutoGenerateColumns set to AutoGenerateColumns="true" and the gridview was directly bounded from a dataset in codebehind. Thus, we don't have boundfields to set the width of columns individually. I tried a lot of methods found over the internet but sadly anyone could not help me. But I have overcome the problem using some tricks and am now sharing this article with all of you so that if anyone has a problem like me, he will not get more frustrated.


I used many methods found over the internet, but they could not work for me. Then I used both methods - that is one for bound field and another for setting the AutoGenerateColumns="true" - individually in two projects and then when page got rendered in browser, I used "View Source" functionality of browser and then realized what is the main difference in both types.

Using the Code

First, I created a sample webpage in ASP.NET 3.5. I also attached the source code in a zipped file.

Below is the aspx page:
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="GridViewWidth._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >
<head  runat="server">
    <form id="form1"  runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" 


        style="table-layout:fixed;" Width="1000px">        
        <!-- Mind the above two lines to make this trick effective you must have to use both properties as is; -->

Code behind file:
Imports System.Data.SqlClient
Partial Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim strCon As New SqlConnection("Data Source=myDataSource;Initial Catalog=myDataBaseName;Persist Security Info=True;User ID=GKRANJAN;Password=abcdef")
        Dim da As New SqlDataAdapter("Select * from myTableName", strCon)
        Dim ds As New DataSet
        GridView1.DataSource = ds
    End Sub

    Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.Header Then

            'For first column set to 200 px
            Dim cell As TableCell = e.Row.Cells(0)
            cell.Width = New Unit("200px")

            'For others set to 50 px
            'You can set all the width individually

            For i = 1 To e.Row.Cells.Count - 1
                'Mind that i used i=1 not 0 because the width of cells(0) has already been set
                Dim cell2 As TableCell = e.Row.Cells(i)
                cell2.Width = New Unit("10px")
        End If
    End Sub
End Class

Please mind two things in .aspx:

Actually, when we use boundfields then gridview columns width renders in browser as we set the widths of each and every columns until overflow condition occurs. In overflow condition, browser uses its mind and sets it to some values so that it can be readable to user.

In my scenario, I saw that if I am using bound field for gridview, it adds the following in rendered source:

Then I understood the actual problem that even I am using the code written below, it was not working. Then I added the lines defined in "Please mind two things in .aspx"

Points of Interest

What I used in code behind, you can get it if you will give some time in searching the same over the internet, but it's tough to find the factor by which I fixed my bug. Because I could not get anything like that over the internet, I am sharing my trick with all of you. I used in .aspx page to fix the layout of table. Hence gridview renders as table in browser.



Added source code


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


About the Author

Gopal Krishna Ranjan
Software Developer (Senior)
India India
Working since 2010 in Database, Windows and Web Apps development. I always try to help others as best as possible through knowledge sharing. I am Cool and dedicated to my work with a deep Believe in knowledge sharing.
I have Extensive experience in Database performance tuning and optimization with SQL Server 2012, 2008 and 2005, which includes Query Analysis, Query Design Analysis, System Performance Analysis, Index Analysis, Lookup Analysis, Statistics Analysis, Fragmentation Analysis, Execution Plan Analysis, Blocking Analysis, Deadlock Analysis, Cursor Cost Analysis, Database Performance Testing, Database Workload Optimization.
Also have Strong experience on SSRS (SQL Server Reporting Services), Intermediate level in SSIS and Beginning level in SSAS.

You may also be interested in...

Comments and Discussions

GeneralTHANK YOU Pin
Member 105140089-Jan-14 6:08
memberMember 105140089-Jan-14 6:08 
GeneralMy vote of 4 Pin
vwynn19-Feb-13 12:08
membervwynn19-Feb-13 12:08 
QuestionGreat suggestion Pin
itsme.richa5-Nov-12 19:28
memberitsme.richa5-Nov-12 19:28 
GeneralMy vote of 5 Pin
Аslam Iqbal17-Jun-12 5:01
memberАslam Iqbal17-Jun-12 5:01 
SuggestionSetting the width Pin
razarizvi6-Jun-12 10:32
memberrazarizvi6-Jun-12 10:32 
GeneralRe: Setting the width Pin
Аslam Iqbal17-Jun-12 5:05
memberАslam Iqbal17-Jun-12 5:05 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.180111.1 | Last Updated 21 Dec 2011
Article Copyright 2011 by Gopal Krishna Ranjan
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid