Set Width of gridview columns dynamically when AutoGenerateColumns="true"

26,484

Solution 1

I got it.

Below is the .aspx page: -

<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>

And this is the Code behind: -

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 

Actually when we use boundfields then gridview columns width renders in browser as we set the widths of each and every columns. I used two methods in two projects - that is one by taking bound fields with AutoGenerateColumns="false" and another by setting the AutoGenerateColumns = "true" - individually in two project and then when page got rendered in browser, i used "View Source" functionality of browser and then realized that what is the main difference in both types. The difference is as: -

style="table-layout:fixed;" 

I also added the below lines in my .aspx page at gridview tag: -

style="table-layout:fixed;" Width="1000px" 

And now it's working fine.

Thanks to All!!

Solution 2

I dont know if its just a typo(or you omitted it) but your code on the RowDataBound part is missing the IF part..

But youre on the right track. Me, i use some thing like this and it works all the time

Protected Sub gvData_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvData.RowDataBound
     If e.Row.RowType = DataControlRowType.DataRow Then
            e.Row.Cells(0).Width = New Unit("200px")
            e.Row.Cells(1).Width = New Unit("500px")
     End If
 End Sub

But remember, the gridview is rendered a table. So cells will resize itself to the longest content.

Solution 3

If you are not intending to make the grid in fixed mode (ie. expecting a overflow behaviour as there are large number of columns) then the above solution with style="table-layout:fixed;" is not the appropriate one.

e.g. see the below scenario:

<div style="overflow:auto;">
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"></asp:GridView>
</div>

In this such case just set the cell Width to specific value and Set Cell Wrap to False

Protected Sub gvData_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvData.RowDataBound
     If e.Row.RowType = DataControlRowType.DataRow Then
        e.Row.Cells(0).Width = New Unit("200px") 
        e.Row.Cells(0).Wrap = false
     End If
End Sub
Share:
26,484
Gopal Krishna Ranjan
Author by

Gopal Krishna Ranjan

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.

Updated on July 09, 2022

Comments

  • Gopal Krishna Ranjan
    Gopal Krishna Ranjan almost 2 years

    I have a problem in setting the width of the gridview when i used the property AutoGenerateColumns to AutoGenerateColumns="true". And the gridview is databind in code behind. If i am using gridview1.columns(0).width it raise error.

    And the GridView1.Columns.Count is always zero because the grid view is databind.

    In .aspx: -

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
    </asp:GridView>
    

    In code behind

    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()
    

    Hence myTableName has more columns and i dont like to add them through BoundFiled because they vary in my case.

    In GridView1_RowDataBound i used : -

    Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    Dim cell As TableCell = e.Row.Cells(0)
                cell.Width = New Unit("200px")
        End Sub
    

    But it could not work for me. Please help me!!

    Thanks to all!!

    • Yuriy Rozhovetskiy
      Yuriy Rozhovetskiy over 12 years
      Provide a full RowDataBound method body. What do you check in it with If clause?
    • Gopal Krishna Ranjan
      Gopal Krishna Ranjan over 12 years
      @YuriyRozhovetskiy sorry it was added by mistake. Thanks.
  • Gopal Krishna Ranjan
    Gopal Krishna Ranjan over 12 years
    The same happened with me. The table is resized and all the work done becomes worthless. @noisyass2
  • Wilhelm
    Wilhelm about 3 years
    For me it worked well without the : Width="1000px" But maybe this is, because I use something like cell2.Width = New Unit("10%") and calculate the width fo each cell in percent.