Click here to Skip to main content
15,843,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Does anyone know how to get the underlying datafield properties from a gridview column?

Specifically, I am interested in getting the name and type of the datafield.

Something like
C#
for (int x = 0; x < grdCustList.Columns.Count; x++)
{
          //get the columns underlying datafield name and type
}

Thanks in advance!
Posted
Updated 27-Sep-12 6:56am
v2

1 solution

Lets say, you have all bound fields. Following code should do:
C#
foreach (System.Web.UI.WebControls.BoundField bfName in grdCustList.Columns)
{
    string currentDataField =  bfName.DataField;
    // Do whatever you want to with it here.
}
 
Share this answer
 
Comments
Christopher Devous 27-Sep-12 12:44pm    
I think this would work, execpt that the first two columns are template fields. I get "Unable to cast object of type 'System.Web.UI.WebControls.TemplateField' to type 'System.Web.UI.WebControls.BoundField'"

I can't figure out how to iterate the columns and figure out if I'm dealing with a boundfield or a template field.

Basically, I am trying to create a datatable containing the gridview contents without rebinding to get the table structure.

What I'm trying to do is create a method that will export a grid to excel without rebinding, and I'd like it to do so by figuring out how the grid is constructed.

Presently, I create a datatable (grdDT), add columns to the datatable using the columns.add method (which requires a name and data type), then iterate the gridview rows and add the contents to the datatable like so:

foreach (GridViewRow r in grdCustList.Rows)
{
DataRow dr = grdDT.NewRow();
for (int idx = 0; idx < r.Cells.Count; idx++)
{
dr[idx] = r.Cells[idx].Text.Trim().Replace(" ", "");
}
grdDT.Rows.Add(dr);
}

Then I instantiate a datagrid and bind it to grdDT and use the htmlwriter to render it out to excel.

This all works fabulously well, but it would be more reuseable if I could figure out how to build the table from the structure of the grid.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900