Posts
208
Comments
1144
Trackbacks
51
GridView - Set column properties at run-time

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 Print
Comments
Gravatar
# re: GridView - Set column properties at run-time
Brian
3/31/2006 10:42 AM
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");
}
}
Gravatar
# re: GridView - Set column properties at run-time
Steve
3/31/2006 10:51 AM
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.
Gravatar
# re: GridView - Set column properties at run-time
Sen
4/2/2007 8:53 AM
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}";
}
Gravatar
# re: GridView - Set column properties at run-time
Miguel Angel
7/18/2007 7:04 AM
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;
}
Gravatar
# re: GridView - Set column properties at run-time
misguided
7/24/2007 6:53 PM
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).
Gravatar
# re: GridView - Set column properties at run-time
Some.Net(Guy)
9/24/2007 7:34 PM
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.
Gravatar
# re: GridView - Set column properties at run-time
Took Way to Long
1/18/2008 1:05 AM
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.
Gravatar
# re: GridView - Set column properties at run-time
Lakshmi
5/18/2008 2:49 AM


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
Gravatar
# re: GridView - Set column properties at run-time
Geetha
5/28/2008 4:01 AM
Hi all,

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

Gravatar
# re: GridView - Set column properties at run-time
Ross
8/11/2008 12:39 PM
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?
Gravatar
# re: GridView - Set column properties at run-time
Ralph Hulslander
9/9/2008 11:39 PM
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
Gravatar
# re: GridView - Set column properties at run-time
Ralph Hulslander
9/24/2008 9:30 AM
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
Gravatar
# re: GridView - Set column properties at run-time
maroof
11/25/2008 12:53 AM
Hi all,

I have gidview with plenty of columns then why columns count is always zero.....
Gravatar
# GridView - Set column properties at design time
H. S.
12/4/2008 4:21 PM
Hi,

Is it possible to combine more than one column of the target table
into one column of the GridView?

If yes, what is the syntax?

Thanks
Gravatar
# re: GridView - Set column properties at run-time
Steve
12/4/2008 4:35 PM
H.S. - It depends what kind of column you're trying to use. If it's a BoundField, then no - that can only take 1. HyperLinkField can take multiple but may not be what you're after. You can always use a template field and customize however you like.
Gravatar
# re: GridView - Set column properties at run-time
uglyden
2/23/2009 3:17 PM
Do to Add a new Template field on fly?
Gravatar
# re: GridView - Set column properties at run-time
Prabhat
3/20/2009 9:10 AM
how can we set the datafield property of databoundcolumn in c# code?
please answer ASAP as i m stuck on it.
tahnks in advance.
Gravatar
# re: GridView - Set column properties at run-time
Steve
3/20/2009 9:19 AM
The code is right in the post above:
someField.DataField = "Price";

What does your code look like? Are you getting exceptions?
Gravatar
# re: GridView - Set column properties at run-time
ken s
5/5/2009 7:09 AM
I am not able to get this to work ...

e.Row.Cells[FindColumn(e, "Apps")].Text = e.Row.Cells[FindColumn(e, "ThisColumn")].Text.ToString("C");

Error Message ...
CS0103: The name 'FindColumn' does not exist in the current context
Gravatar
# re: GridView - Set column properties at run-time
Steve
5/5/2009 9:50 AM
@kens - If that line of code in in your code behind, then yes, that error is correct - it's telling you that the Page class does not have a method called FindColumn(). I'm not sure where you're getting that FindColumn() method from.
Gravatar
# re: GridView - Set column properties at run-time
mf
7/10/2009 6:31 AM
If you're Gridview columns are AutoGenerated, in order to set Gridview's column width dynamically based on Column header's title, I used the code snippet below. I placed the code after I called gdvComp.Databind(). I had set my width to what is the max data/field length in the database, since I just want to set it once based on my requirements.

For i As Integer = 0 To gdvComp.HeaderRow.Cells.Count - 1
If InStr(gdvComp.HeaderRow.Cells(i).Text.ToLower, "ColumnHeaderTitle1") > 0 Then
gdvComp.HeaderRow.Cells(i).Width = Unit.Pixel(2000)
ElseIf InStr(gdvComp.HeaderRow.Cells(i).Text.ToLower, "ColumnHeaderTitle2") > 0 Then
gdvComp.HeaderRow.Cells(i).Width = Unit.Pixel(2000)
ElseIf InStr(gdvComp.HeaderRow.Cells(i).Text.ToLower, "ColumnHeaderTitle3") > 0 Then
gdvComp.HeaderRow.Cells(i).Width = Unit.Pixel(2000)
Else 'other columns
gdvComp.HeaderRow.Cells(i).Width = Unit.Pixel(500)
End If
Next

If you want to set the column width dynamically based on the individual cell data, see microsoft article below:
http://msdn.microsoft.com/en-us/library/ms178296(VS.80).aspx

Hope that helps. Thanks.
Gravatar
# re: GridView - Set column properties at run-time
jia
2/4/2010 1:38 AM
how to change datagridview cell or column style to buttons at run time
Gravatar
# re: GridView - Set column properties at run-time
sumit
5/11/2010 8:12 AM
in gridview how can i merge 4 columns in to one having property autogeneratecolumns true
Gravatar
# re: GridView - Set column properties at run-time
TMS
9/8/2010 4:25 PM
Try this after the GV is bound. What you are doing here is grabbing the contents of each headercell and replacing it with a Label of width = 200. This will replace your GV header text formatting with your label formatting, so you will may have to diddle your SKIN or CSS file.

This example also center-aligns the column header label.

for (int x=0;x<gv.HeaderRow.Cells.Count;x++){
TableCell hyp = new TableCell();
hyp = (TableCell) gv.HeaderRow.Cells[x];
Label llbl = new Label();
llbl.Text =gv.HeaderRow.Cells[x].Text;
llbl.Width = 200;
hyp.HorizontalAlign = HorizontalAlign.Center;
hyp.Controls.Add(llbl);
}
Gravatar
# GridView - Set column properties at run-time
Linda Gilbert
12/8/2010 9:53 AM
Good morning, I have been racking my brain to set grid column formats at run time and have had no luck. Column 1 is to be invisible, columns 3 and 4 are to show date only and column 5 is to be shown as currency. Any direction you could provide to me would be greatly appreciated. Here is my code:

Private Sub Load_Active_Grid()
Dim tempemployee As String
tempemployee = Session("EmployeeId")
Dim connectString As String
Dim sqlString As String
Dim ObjConnection As OleDbConnection
Dim objCmd As OleDbDataAdapter
Dim DS As New DataSet
Dim cols As String
connectString = "Provider=OLEMySQL.MySQLSource.1; Data Source=Trentserv; User ID=expense; Password=dataconnect; Initial Catalog=expense;"
cols = "hist_expense_header_id as 'Expense #',hist_expense_desc as 'Description', hist_date_start as 'Start Date', hist_date_end as 'End Date', hist_total_expense as 'Total Expense'"
sqlString = "SELECT " + cols + " FROM View_tbl_hist_expense_header_active where employee_id = '" + tempemployee + "' ORDER BY hist_date_start DESC"
Session("LastSQL1") = sqlString
ObjConnection = New OleDbConnection(connectString)
objCmd = New OleDbDataAdapter(sqlString, ObjConnection)
ObjConnection.Open()
objCmd.Fill(DS)
GridView1.DataSource = DS
GridView1.DataBind()
If (GridView1.Columns.Count > 0) Then
GridView1.Columns[0].Visible = visiblity.collapsed
GridView1.Columns[3].DataFormatString = "{0:D}"
GridView1.Columns[4].DataFormatString = "{0:D}"
GridView1.Columns[5].DataFormatString = "{0:C}"
End If

ObjConnection.Close()
End Sub
Gravatar
# re: GridView - Set column properties at run-time
Steve
12/10/2010 7:22 AM
@Linda - Try calling the DataBind() method *after* setting all of those properties.
Gravatar
# re: GridView - Set column properties at run-time
Linda Gilbert
12/13/2010 9:32 AM
Hi Steve, I did try calling method after setting properties, no luck. When I un-comment the code within the if statement "If (GridView1.Columns.Count > 0) Then" all of the lines referencing Gridview1.columns.. are highlighted in blue and the message is "Property access must assign to the property or use its value." Could I be missing something like a reference, import, etc. Linda
Gravatar
# re: GridView - Set column properties at run-time
jad
3/30/2011 5:20 AM
do colspan like this,

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[1].Visible = false;
e.Row.Cells[2].ColumnSpan = 2;
e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Center;
e.Row.Cells[2].Text = "Service Name";
}
}
Gravatar
# how to arrange gv columns at runtime
kb soomro
5/31/2011 3:06 AM
hi i am new to asp.net and i want to gv columns at runtime
for i.e
current position of gv columns

1 answerId
2 answerText
3 questionId

require arrangement
1 answerId
2 questionId
3 answerText

kindly help me
Gravatar
# re: GridView - Set column properties at run-time
Pawan
9/6/2011 8:16 AM
If my application i used this code and i want to hide the boundfield EmployeeCode from this but i couldnot get the EmployeeCode value after setting visibility to false..
Please help me..

Code is like this

Private Sub BindGridEmp()
Try
grdViewEmployeeAdded.Columns.Clear()

Dim mSelect As New CommandField
mSelect.HeaderText = "Select"
mSelect.ButtonType = ButtonType.Link
mSelect.ShowSelectButton = True
'mSelect.ShowEditButton = True
'mSelect.SelectText = ("Select")
grdViewEmployeeAdded.Columns.Add(mSelect)

Dim PaySlipCode As New BoundField
PaySlipCode.HeaderText = "PaySlipCode"
PaySlipCode.DataField = "PaySlipCode"
grdViewEmployeeAdded.Columns.Add(PaySlipCode)

Dim EmployeeCode As New BoundField
EmployeeCode.HeaderText = "Employee Code"
EmployeeCode.DataField = "EmployeeCode"
grdViewEmployeeAdded.Columns.Add(EmployeeCode)
'***********************************************************
Dim EmployeeName As New BoundField
'EmployeeName.HeaderText = "Employee Name"
EmployeeName.DataField = "FirstName"
grdViewEmployeeAdded.Columns.Add(EmployeeName)
grdViewEmployeeAdded.Columns(3).ItemStyle.Width = 200
grdViewEmployeeAdded.Columns(3).HeaderText = "Employee Name"
grdViewEmployeeAdded.Columns(3).HeaderStyle.Width = 200

'Dim UnitName As New BoundField
'UnitName.HeaderText = "Unit Name"
'UnitName.DataField = "UnitName"
'grdViewEmployeeAdded.Columns.Add(UnitName)
'***********************************************************

Dim UnitCode As New BoundField
UnitCode.HeaderText = "Unit Code"
UnitCode.DataField = "UnitCode"
grdViewEmployeeAdded.Columns.Add(UnitCode)

Dim Month As New BoundField
Month.HeaderText = "Month"
Month.DataField = "Month"
grdViewEmployeeAdded.Columns.Add(Month)

Dim Year As New BoundField
Year.HeaderText = "Year"
Year.DataField = "Year"
grdViewEmployeeAdded.Columns.Add(Year)

Dim mRemove As New CommandField
mRemove.HeaderText = "Remove"
mRemove.ButtonType = ButtonType.Link
' mRemove.ShowSelectButton = True
mRemove.ShowDeleteButton = True
grdViewEmployeeAdded.Columns.Add(mRemove)


grdViewEmployeeAdded.DataSource = ds2
grdViewEmployeeAdded.DataBind()

grdViewEmployeeAdded.Columns(1).Visible = False
' ***********************************************************
grdViewEmployeeAdded.Columns(2).Visible = False
grdViewEmployeeAdded.Columns(4).Visible = False
grdViewEmployeeAdded.Columns(5).Visible = False
grdViewEmployeeAdded.Columns(6).Visible = False
'***********************************************************
pintUnitCode = ddlUnitCode.SelectedValue
ds = objClsEmployeeMaster.GetPaySlipDataForUnit(pintUnitCode)
Me.BindGridView()


Catch ex As Exception

End Try
End Sub
Gravatar
# re: GridView - Set column properties at run-time
Tobias
10/11/2013 5:28 AM
Set column properties,
http://www.kettic.com/winforms_ui/csharp_guide/gridview_properties.shtml
Gravatar
# re: GridView - Set column properties at run-time
VETRY
11/22/2014 3:37 AM
PNRNo FlightNo FName LName
HA13000001 HA101 GHJF Syeda
HA13000002 JG Syeda
HA13000003 HA103 FGH Syeda
HA13000004 FHG Syeda
HA13000005 Yaseen Syeda
HA13000006 HA106 Abidul Syed

How to i give hyperlink for FlightNo column by using devexpress gridview and how to i show Norecords for NULL values in FlightNo column?
Give me solution for this.

Post Comment

Title *
Name *
Email
Comment *  
Verification

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud