【问题标题】:How to set columns width in a Dynamic Gridview?如何在动态 Gridview 中设置列​​宽?
【发布时间】:2015-06-08 05:29:47
【问题描述】:

如何在动态 Gridview 中设置列​​宽?当 AutoGenerateColumns="true"

【问题讨论】:

标签: c# asp.net gridview


【解决方案1】:

你可以有一个serverside 方法如下:

private void GV_RowDataBound(object o, GridViewRowEventArgs e)
{        
   // apply custom formatting to data cells
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
       // set formatting for the category cell
       TableCell cell = e.Row.Cells[0];
       cell.Width = new Unit("120px");
       cell.Style["border-right"] = "2px solid #666666";

       // set formatting for value cells
       for(int i=1; i<e.Row.Cells.Count; i++)
       {
            cell = e.Row.Cells[i];
            // right-align each of the column cells after the first
            // and set the width
            cell.HorizontalAlign = HorizontalAlign.Right;
            cell.Width = new Unit("90px");
            // alternate background colors
            if (i % 2 == 1)
                  cell.BackColor 
                      =  System.Drawing.ColorTranslator.FromHtml("#EFEFEF");
                  // check value columns for a high enough value
                  // (value >= 8000) and apply special highlighting
            }                    
        }

        // apply custom formatting to the header cells
        if (e.Row.RowType == DataControlRowType.Header)
        {
            foreach (TableCell cell in e.Row.Cells)
            {
                cell.Style["border-bottom"] = "2px solid #666666";
                cell.BackColor=System.Drawing.Color.LightGray;
            }
        }

    }
}

您的aspx 页面

<asp:GridView id="myList" runat="server"
                  AutoGenerateColumns="true"
                  OnRowDataBound="GV_RowDataBound"
                  . . . 
                  >
</asp:GridView> 

详细信息可以查看here

【讨论】:

  • 默认情况下 AutoGenerateColumns 是 "true" ,所以没必要提
  • 我同意,但我认为你也需要检查你的答案,正如你提到的那样默认情况下 autogeneratecolumn 是 false 所以不需要指定 autogeneratecolumn="true" :)
【解决方案2】:

你需要像这样改变gridview的RowDataBound事件

  protected void gvData_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
   {
     if (e.Row.RowType == DataControlRowType.DataRow) {
       e.Row.Cells(0).Width = new Unit("200px");
       e.Row.Cells(1).Width = new Unit("500px");
   }
  }

你的标记

 <asp:GridView id="gvData" runat="server"                 
              OnRowDataBound="gvData_RowDataBound">
 </asp:GridView> 

默认情况下 autogeneratecolumn 为 false,因此无需指定 autogeneratecolumn="true"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-05
    • 2011-10-10
    • 2015-11-25
    • 2020-11-28
    • 2017-09-13
    • 2012-01-21
    • 2012-12-18
    • 2014-01-19
    相关资源
    最近更新 更多