Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Datagrid column headers

Status
Not open for further replies.

plsh

Programmer
Mar 5, 2003
118
ZA
Good day,

I have a problem that is really irratating. I have a datagrid that is bound. It is automatically filled with all the fields in the dataset. The only thing is that when the datagrid is populated the column order is different to that of the dataset. I don't mind the columns been all jumbled up but I do need to know which column is where.

So my question is, is there a way in which I can read the column header text directly from the datagrid as the datagrid and dataset column order do not match and need the order of the datagrid?

Cheers
 
Here are an example which I have to make columns from a dataset to Excel.

Code:
int colIndex = 0;
foreach(DataColumn col in dataSet.Tables["Result"].Columns)
{
   colIndex++;	
   excel.Cells[1,colIndex]=col.ColumnName;			
}
 
Hi sbdSolna,

Thanks, but that unfortunately doesnt help me at all. The order of the columns is different in the dataset and the datagrid, I need to and have to read the column headers out of the datagrid. I cannot access the dataset in a conventional way as you have, I HAVE TO ACCESS THE DATAGRID.

THANKS IN ADVANCE
 
if you know what type is the DataSource of the DataGrid, you can cast it and then access all the data you need, including the column names.

--------------------------
"two wrongs don't make a right, but three lefts do" - the unknown sage
 
Hi again
---------
Here is the solution

Code:
				DataGridTableStyle dgtStyle = dataGrid.TableStyles[0];
				foreach(DataGridColumnStyle gcs in dgtStyle.GridColumnStyles) {
					colIndex++;	
					excel.Cells[rowIndex,colIndex]=gcs.HeaderText;
				}
	
				DataView dataView = (DataView) ((CurrencyManager) dataGrid.BindingContext[dataGrid.DataSource,
					dataGrid.DataMember]).List;
			
				foreach(DataRow dr in dataView.Table.Rows) {
					// iterate the cells
					rowIndex++; 
					colIndex = 0; 
					foreach(DataGridColumnStyle gcs in dgtStyle.GridColumnStyles) {
						colIndex++;
						excel.Cells[rowIndex,colIndex] = dr[gcs.MappingName];
					}
				}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top