【问题标题】:GridView - set width of column in code behind (AutoGenerateColumns="true")GridView - 在后面的代码中设置列的宽度 (AutoGenerateColumns="true")
【发布时间】:2015-12-18 13:40:15
【问题描述】:

我的网格视图:

<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 已成功填充。
请注意,我可以设置列的对齐方式和背景色,但不能设置其宽度。
我尝试了许多解决方案,但都没有奏效。
它总是将列的大小调整为最长的内容。
能做到吗……?

【问题讨论】:

  • 试想一下,表格中的单个单元格如何具有不同的宽度。列可以有宽度,而不是单元格。
  • 行不能有不同的列宽。所有这些都应该使用样式表进行设置。
  • 是的。我应该练习我的英语。与此同时,我正在寻找一种从后面的代码中设置列宽的方法。 (我会改一下标题,谢谢你的评论)。
  • @wolfeh - 我尝试使用样式表(请参阅上面代码中的最后一行)。在 css 中我只有:width: 150px;但这也无济于事。某处我做错了什么,我无法弄清楚它是什么......

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


【解决方案1】:

我可以使用 RowCreated 事件来做到这一点,但我必须设置网格的宽度并将网格设置为 table-layout:fixed

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

}

【讨论】:

    【解决方案2】:

    asp:GridView 呈现为 HTML 表格,因此您只需要使用 CSS 设置列宽

    th, td {
        width: 120px;
    }
    

    【讨论】:

    猜你喜欢
    • 2012-01-21
    • 2012-09-20
    • 2018-08-13
    • 2011-11-25
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 2013-06-20
    • 2014-01-19
    相关资源
    最近更新 更多