0

我有一个带有自动生成列的gridview,我以编程方式设置了我想格式化列宽。这是我在后面的代码中为我的 gridview 编写的代码...

If Not Page.IsPostBack Then
    Dim budgetTable As New DataTable("Budgets")

    budgetTable.Columns.Add("Approval Date", GetType(Date))
    budgetTable.Columns.Add("Total Amount", GetType(String))
    budgetTable.Columns.Add("Comments", GetType(String))
    budgetTable.Columns.Add("Initials", GetType(String))

    Try
        For i As Integer = 0 To 0
            Dim tableRow As DataRow = budgetTable.NewRow()
            tableRow("Approval Date") = Date.Today
            tableRow("Total Amount") = ""
            tableRow("Comments") = ""
            tableRow("Initials") = ""
            budgetTable.Rows.Add (tableRow)
        Next
        Session("BudgetsTable") = budgetTable
        BindData()
    Catch ex As Exception

    End Try
End If

这是html端的gridview:

<asp:GridView ID="gvOLIAdj" runat="server" CssClass="td8" CellPadding="4" ForeColor="#333333" PageSize="2" ViewStateMode="Enabled">
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />

    <Columns>
        <asp:CommandField EditText="Add" ShowEditButton="True" />
    </Columns>

    <EditRowStyle BackColor="#999999" />
    <FooterStyle BackColor="#003399" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="White" />
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#E9E7E2" />
    <SortedAscendingHeaderStyle BackColor="#506C8C" />
    <SortedDescendingCellStyle BackColor="#FFFDF8" />
    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
4

2 回答 2

1

- 编辑 -

(在阅读了 OP 的评论后删除了旧内容,因为这无济于事)

尝试使用 RowDataBound 事件来设置宽度(或任何其他属性)。

未经测试的代码:

Protected Sub gvOLIAdj_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvOLIAdj.RowDataBound
    If (e.Row.RowType = DataControlRowType.Header) Then
        e.Row.Cells(0).Width = 100  '100 pixels
        e.Row.Cells(1).Width = 50
        e.Row.Cells(2).Width = 200
        e.Row.Cells(3).Width = 150
    End If
End Sub

如果上述方法不起作用,请尝试将其设置为e.Row.RowType = DataControlRowType.DataRow.

于 2012-05-30T13:28:50.450 回答
0

我会使用样式表来完成它:

.td8 td:nth-child(3) {
    width: 100px;
}

假设您希望第三列为 100px。这是一个 CSS3 选项,因此它只适用于较新的浏览器。

编辑: 阅读您对@Pradeep Kumar 所做的评论,您可能过早将宽度应用于列。Page_PreRender在绑定和创建 GridView 之后,尝试在事件中进行这些更改。请记住,在RowItemCreated 事件完全完成之前,GridView 中的列不存在。

于 2012-05-30T13:32:50.563 回答