Search code examples
gridviewdatatabledatagridviewcolumncolumn-width

Set width of columns in dynamically created gridview


I am new in this field and right now I am facing a problem in setting the column width for my dynamically created GridView. Below is my code:

Using dt As New DataTable()
    sda.Fill(dt)

    Dim mygrid As New GridView

    mygrid.AutoGenerateColumns = "true"
    mygrid.Font.Size = FontSize.Large
    mygrid.GridLines = GridLines.None
    mygrid.HeaderStyle.HorizontalAlign=HorizontalAlign.Left

    mygrid.HeaderStyle.CssClass = "single_header"

    mygrid.ShowFooter = True

    mygrid.DataSource = dt

    mygrid.Width = "700"

    dt.Columns(0).ColumnName = "Specification"
    dt.Columns(1).ColumnName = "Hours"
    dt.Columns(2).ColumnName = "Minutes"
    dt.Columns(3).ColumnName = "Cost"

    mygrid.DataBind()
End Using

Solution

  • You have to do it in RowCreated event of your GridView as like below example. You can add RowCreated event dynamically as like:

    mygrid.RowDataBound += new EventHandler(GridView1_RowCreated);
    

    VB.NET code:

    Private Sub GridView1_RowCreated(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
    

    Asp.net Code:

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if ((e.Row.RowType == DataControlRowType.Header))
        {
            // For first column set to 200 px
            TableCell cell = 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; (i 
                        <= (e.Row.Cells.Count - 1)); i++) {
                // Mind that i used i=1 not 0 because the width of cells(0) has already been set
                TableCell cell2 = e.Row.Cells[i];
                cell2.Width = new Unit("10px");
            }
        }
    }