GridView - 在代码后面设置列的宽度(AutoGenerateColumns =" true")

时间:2015-09-21 18:33:30

标签: asp.net gridview width code-behind autogeneratecolumn

我的GridView:

<asp:GridView ID="GridView1" runat="server"
    OnRowDataBound="GridView1_RowDataBound"
    AutoGenerateColumns="true"
    DataKeyNames="Role_id">
</asp:GridView>

在代码背后:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
       //e.Row.Cells[2].Width = 120;                      // isn't working....
    }
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Cells[2].Width = new Unit(120);             // isn't working....
        TableCell cell = e.Row.Cells[2];
        cell.HorizontalAlign = HorizontalAlign.Right;           //**** does work!
        cell.BackColor = Color.LightGray;                       //**** does work!
        //cell.Width = 120;                               // isn't working....
        //e.Row.Cells[2].Width = new Unit("120px") ;      // isn't working....
        //e.Row.Cells[2].CssClass = "myGV_Cell_Width";    // isn't working....
    }
}

GridView已成功填充 请注意,我可以设置列的对齐方式和背景色,但不能设置其宽度 我尝试了许多解决方案,但都没有效果 它总是将列调整为最长的内容 它可以完成吗??

2 个答案:

答案 0 :(得分:2)

我能够使用RowCreated事件来完成它但我必须设置网格的宽度并将网格设置为表格布局:固定

<asp:GridView ID="GridView1" runat="server"
    style="table-layout:fixed;" Width="1000px"
    OnRowCreated = "GridView1_RowCreated"
    OnRowDataBound="GridView1_RowDataBound"
    AutoGenerateColumns="true"
    DataKeyNames="Role_id">
</asp:GridView>

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{

 e.Row.Cells[0].Width = New Unit("220px");

}

答案 1 :(得分:0)

asp:GridView呈现为HTML表,因此您只需使用CSS

设置列宽
th, td {
    width: 120px;
}