Click here to Skip to main content
15,892,161 members
Articles / Web Development / HTML
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.89/5 (11 votes)
21 Dec 2011CPOL2 min read 120K   9   6
Set Width of gridview columns dynamically when AutoGenerateColumns=“true”

Introduction


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.

Background


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:
ASP.NET
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="GridViewWidth._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head  runat="server">
    <title></title>
</head>
<body>
    <form id="form1"  runat="server">
    <div>
        <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; -->
        
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Code behind file:
VB
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
        da.Fill(ds)
        GridView1.DataSource = ds
        GridView1.DataBind()
    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")
            Next
        End If
    End Sub
End Class

Please mind two things in .aspx:
HTML
style="table-layout:fixed;" 
 Width="1000px"

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:
HTML
style="table-layout:fixed;"

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.

Thanks!!

History


Added source code

License

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


Written By
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.

Comments and Discussions

 
GeneralTHANK YOU Pin
Member 105140089-Jan-14 5:08
Member 105140089-Jan-14 5:08 
GeneralMy vote of 4 Pin
vwynn19-Feb-13 11:08
vwynn19-Feb-13 11:08 
QuestionGreat suggestion Pin
itsme.richa5-Nov-12 18:28
itsme.richa5-Nov-12 18:28 
GeneralMy vote of 5 Pin
Аslam Iqbal17-Jun-12 4:01
professionalАslam Iqbal17-Jun-12 4:01 
SuggestionSetting the width Pin
razarizvi6-Jun-12 9:32
razarizvi6-Jun-12 9:32 
GeneralRe: Setting the width Pin
Аslam Iqbal17-Jun-12 4:05
professionalАslam Iqbal17-Jun-12 4: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.