views:

447

answers:

3

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.

Regards,

Bob Avallone

+2  A: 

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 = 100;
    }
alejandrobog
This fails to compile I get exceptionError 1 'object' does not contain a definition for 'ItemStyle' and no extension method 'ItemStyle' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
Bob Avallone
I just edit the answer you, please try it. Make sure you do this after databinding your grid
alejandrobog
A: 

I'd do it like this:

foreach (DataControlField field in grdIssues.Columns)
{
  field.HeaderStyle.Width = 100;
}
Andreas Strandfelt
This compile by does not work. Only the one column that I added manually, a button, is in the collection of columns.Bob
Bob Avallone
What event are you running the code in? You can't do it in Page_Load. Use grdIssues's Databound event.
Andreas Strandfelt
A: 

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