How to set gridview column width when binding to datatable

I bind a table to gridview in asp.net as such

grdIssues.DataSource = mdtIssues; grdIssues.DataBind(); 

The problem is that I cannot control the width of the column, asp.net seems to have decided what width of each column should be. Methods such as

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

do not work because columns are created dynamically. I cannot believe that there is no way to do this without manually creating each column and filling in each row.

+7
c # gridview gridviewcolumn
source share
5 answers

You do not need to manually create columns to set their width, you can do this

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

I managed to change the width of a specific Gridview column (bound to a Datatable ) with the Datatable event:

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

I like to answer my question when I can so that future users searching for the stream will find the answer.

I could not find a way to do what I wanted. However, I found that if I define the columns myself, I can change the properties. In this example, I would like to center the column data. Something like that.

 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; } 
0
source share

I did it like:

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

I would do it like this:

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

All Articles