在动态创建的 gridview 中设置列​​宽

Set width of columns in dynamically created gridview

我是这个领域的新手,现在我在为动态创建的 GridView 设置列宽时遇到问题。下面是我的代码:

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

您必须在 GridView 的 RowCreated 事件中执行此操作,就像 below example 一样。您可以像这样动态添加 RowCreated 事件:

mygrid.RowDataBound += new EventHandler(GridView1_RowCreated);

VB.NET代码:

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代码:

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");
        }
    }
}