How to Set a gridview column width when binding to

2020-03-17 03:37发布

问题:

I am binding a table to a gridview in asp.net as such

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. 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.

回答1:

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


回答2:

I was able to change the width of a certain Gridview column (bound to a Datatable) with the RowDataBound event:

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


回答3:

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;
}


回答4:

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


回答5:

I'd do it like this:

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