Steve Michelotti

C#, ASP.NET, and other stuff

  Home  |   Contact  |   Syndication    |   Login
  50 Posts | 1 Stories | 150 Comments | 52 Trackbacks

News



Tag Cloud


Archives

Post Categories

Image Galleries

Articles

Blogs

An interesting issue came up today that, although it now looks simple, did not have an immediately obvious solution.  Specifically, what if you want to set properties of individual columns of a GridView at run-time (via C# code) rather than at design time in the aspx code.

For example, let's say you want to set the DataFormatString property of a BoundField column.  In short, it is a 2-part solution.  First, you must positionally extract your column out of the GridView's Columns property while casting it to your desired type (in this case a BoundField).  Second, after you have set the properties, do the databind.  So if you have column that you want to format as currency, the code might look like this:

BoundField priceField = grid.Columns[0] as BoundField;
priceField.DataFormatString =
"{0:c}";
priceField.HtmlEncode =
false;
grid.DataSource = list;
grid.DataBind();

Note that since you're manually doing the data binding this will preclude you from using the ObjectDataSource in this case (since that happens before your user code in the Page_Load event).

Taking this one step further, you could even add columns dynamically at run-time doing this:

BoundField someField = new BoundField();
someField.DataField =
"Price";
someField.DataFormatString =
"{0:c}";
someField.HtmlEncode =
false;
grid.Columns.Add(someField);

Note: One reason this might throw you off at first is that in the C# intellisense, BoundColumn comes up first and if you're not watching carefully you might try to use that instead of BoundField which will prevent you from compiling!

posted on Thursday, March 30, 2006 6:51 PM

Feedback

# re: GridView - Set column properties at run-time 3/31/2006 10:42 AM Brian
A couple of notes...

First, you should try to find the column based on it's name rather than its ordinal position. This will allow rearranging and inserting/deleting columns without busting your code. If you change the column name then naturally this will break but you might find the error more recognizable e.g. "Unable to find column 'SomeColumn' instead of 'object or reference not set to an instance blah blah...'.

Second, there is a way you can avoid rebinding the grid. Instead of setting the DataFormatString and HtmlEncode properties for the bound column, you can set them for each tablecell as it is rendered during the RowDataBound event.
e.g.

oublic void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItemIndex > -1)
{
e.Row.Cells[0].Text = e.Row.Cells[0].Text.ToString("C");
//-or- e.Row.Cells[FindColumn(e, "ThisColumn")].Text = e.Row.Cells[FindColumn(e, "ThisColumn")].Text.ToString("C");
}
}


# re: GridView - Set column properties at run-time 3/31/2006 10:51 AM Steve
The GridView's Column property only allow access by ordinal - not by position.

As for the RowDataBound() method - that was the original approach but I wanted to avoid that so I could avoid the overhead of finding a control or column for every single row in the grid.

# re: GridView - Set column properties at run-time 8/1/2006 12:16 AM Hector
string sql = "select Date, SampleSize, Average, Variance, CPK from statisticaDay where id_crit_final_param=@id_crit_final and (Date between @StartDate and @EndDate) and (id_parameter=@id_parameter)";

....
SqlDataSourceHistory.SelectCommand = sql;
SqlDataSourceHistory.Select(new DataSourceSelectArguments());

if (GridView1.Columns.Count > 0)
{
((BoundField)GridView1.Columns[0]).DataFormatString = "{0:dd-MMM-yyyy}";
((BoundField)GridView1.Columns[2]).DataFormatString = "{0:f2}";
}
GridView1.DataBind();

I have this code and the columns count is always 0.

# re: GridView - Set column properties at run-time 4/2/2007 8:53 AM Sen
first do the binding & set the column properties

GridView1.DataBind();
if (GridView1.Columns.Count > 0)
{
((BoundField)GridView1.Columns[0]).DataFormatString = "{0:dd-MMM-yyyy}";
((BoundField)GridView1.Columns[2]).DataFormatString = "{0:f2}";
}

# re: GridView - Set column properties at run-time 7/18/2007 7:04 AM Miguel Angel
It does not work for me. We I do that Columns.Count is always 0.

GridView1.DataBind();

if (GridView1.Columns.Count > 0)
{
GridView1.Columns[0].Visible = false;
}


# re: GridView - Set column properties at run-time 7/24/2007 6:53 PM misguided
Yeah, apparently if you bind a gridView to a datasource and AutoGenerateColumns=true, ASP.NET doesn't add the auto-generated columns to the Columns collection of the gridView. This will only work if your columns are explicitly declared in the <columns> section of the gridView in your aspx (or using the designer, which does the same thing).

# re: GridView - Set column properties at run-time 9/24/2007 7:34 PM Some.Net(Guy)
how do you add a hyperlinkcolumn dynamically at runtime? if you can't add one, how do you modify its properties at runtime? i can't seem to figure out a way to do this.

# re: GridView - Set column properties at run-time 1/18/2008 1:05 AM Took Way to Long
If dynamically creating a gridviews data by binding in codebehind as misguided above mentioned, you cannot access the columns property. I personally needed to set the widths of the columns at runtime and finally found that if you loop through the first rows cells and set each of their widths, it will make each column in the grid behave as desired.

for (int i = 0; i < grdMyGrid.Rows[0].Cells.Count; i++)
{
grdMyGrid.Rows[0].Cells[i].Width = Unit.Pixel(200);
}

Not sure what else this could be useful for, but it helps on the widths.

# re: GridView - Set column properties at run-time 2/4/2008 11:32 AM John
I was wondering if setting columns property at run time will it effect performance compare to if it was set at design time.

Thanks

# re: GridView - Set column properties at run-time 5/18/2008 2:49 AM Lakshmi


Hi Friends,

I am also facing similar to as mentioned above post.

In my page i am binding data dynamically to Grid using ASP.NET and C#. Using AutoGeneratedColumns property of grid, i have set this property to TRUE. so, Howmany ever columns are there in Dataset, that many columns will be created in Grid.
My questions is among those columns in Grid, i have columns like CreatedDate, UpdatedDate and ActionperformedDate. If i want to sort these DATETIME columns , i have to use DataFormatString some where before page is loaded.

Can anyone suggest me how to create BoundFields for Gridview Datetime columns.

Your suggessions are really valuable.


Thanks & Regards,
Lakshmi M


# re: GridView - Set column properties at run-time 5/28/2008 4:01 AM Geetha
Hi all,

Iam having the same problem .i have gidview with plenty of columns then why columns count is always zero.....



# re: GridView - Set column properties at run-time 8/11/2008 12:39 PM Ross
Hi,

I am using the RowDataBound event and wish to add controls to a column depending on the status of on of the data bound fields.

Which is the best field to use for this. I was looking at template field but this didn't seem to work out?

# re: GridView - Set column properties at run-time 9/2/2008 7:49 AM d
dd

# re: GridView - Set column properties at run-time 9/9/2008 11:39 PM Ralph Hulslander
I am new to ASP.NET and C#.

I am trying to populate a DataGrid from a DatSet but nothing appears, the DataGrid is not rendered! How do I make the
DataGrid appear?

Thanks for the help (I really need it)!
Ralph

# re: GridView - Set column properties at run-time 9/24/2008 9:30 AM Ralph Hulslander
The answer to my question was to use % not * in my
Access Query.

A web call (OleDb)to a Acccess DataBase is actually calling the JET database engine which uses a different syntax then Acccess.

Ralph

Post Feedback

Title:
Name:
Email: (never displayed)
Url:
Comments: 
Please add 1 and 2 and type the answer here: