简体   繁体   English

如何在绑定到数据表时设置gridview列宽

[英]How to Set a gridview column width when binding to a datatable

I am binding a table to a gridview in asp.net as such 我正在将表绑定到asp.net中的gridview

grdIssues.DataSource = mdtIssues;

grdIssues.DataBind();

The problem is I cannot then control the column width, asp.net seems to decided on it's own what width each column should be. 问题是我无法控制列宽,asp.net似乎决定了它自己的每列应该是多少宽度。 Methods such as 方法如

 grdIssues.Columns[0].ItemStyle.Width = 100;
 grdIssues.Columns[1].ItemStyle.Width = 100;

don't work because the columns are created dynamically. 不起作用,因为列是动态创建的。 I cannot believe there isn't a way to do this short of manually creating each column and filling each row. 我无法相信没有办法在手动创建每一列并填充每一行时做到这一点。

You dont have to manually create the columns to set them the width, you can do this 您不必手动创建列来设置宽度,您可以这样做

 foreach (DataControlField column in OrdersGV.Columns)
    {
      column.ItemStyle.Width = Unit.Pixel(100);
    }

I was able to change the width of a certain Gridview column (bound to a Datatable ) with the RowDataBound event: 我能够使用RowDataBound事件更改某个Gridview列的宽度(绑定到Datatable ):

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
    e.Row.Cells[0].Attributes["width"] = "200px";
}

I like to answer my own question whenever I can so future users searching the thread will find the answer. 我喜欢随时回答我自己的问题,以便将来搜索帖子的用户都能找到答案。

I could not find a way to do what I wanted directly. 我找不到直接做我想要的方法。 However I found if I define the columns myself, I could change the properties. 但是我发现如果我自己定义列,我可以更改属性。 In this example, I wanted to center the column data. 在这个例子中,我想使列数据居中。 Something like this. 像这样的东西。

BoundField bdfRaisedDate = new BoundField();
clsUtilities.SetBoundFieldCenter(ref bdfRaisedDate, "RaisedDateShort",    "Opened", "RaisedDate");

grdIssues.Columns.Add(bdfRaisedDate);

grdIssues.DataSource = mdtIssues;

grdIssues.DataBind();

public static void SetBoundFieldCenter(ref BoundField bdfAny, string pDataField, string pHeadingValue, string  pSortExpression)
{
      bdfAny.DataField = pDataField;
      bdfAny.HeaderText = pHeadingValue;
      bdfAny.SortExpression = pSortExpression;
      bdfAny.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
      bdfAny.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
}

I did it as: 我做到了:

gridView1.HeaderRow.Cells[0].Attributes["Width"] = "100px";
gridView1.HeaderRow.Cells[1].Attributes["Width"] = "50px";
gridView1.HeaderRow.Cells[2].Attributes["Width"] = "200px";

I'd do it like this: 我这样做:

foreach (DataControlField field in grdIssues.Columns)
{
  field.HeaderStyle.Width = 100;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM