set datatable first row as grid header

徘徊边缘 提交于 2021-02-10 19:57:23

问题


I have a scenario where i am fetching data from xls file using following connection string

mCon.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;data source=" + mstrFilePath + ";Extended Properties=\"Excel 12.0;HDR=NO\";");

and following code

string strSelectQuery = "Select * from [sheet1$]";    
System.Data.OleDb.OleDbCommand= new System.Data.OleDb.OleDbCommand(strSelectQuery, mCon);
DataAdapter = new System.Data.OleDb.OleDbDataAdapter(strSelectQuery, mCon);
DataAdapter.Fill(mDTable);  

Now when i bind this datatable mDtable to gridview, It results in no header row for grid.

But i have another gridview which needs to have header columns as the first row in datatable mDTable.

How can i use same datatable to bind both gridview's one without header row and another with header row ??


回答1:


Harsh solution:

You can sign the column header, using DataTable.Columns[n].ColumnName.

Example (not tested, beware of code error):

int index = 0;
foreach(DataTableColumn col in DataTable.Columns)
{
  col.ColumnName = DataTable.Rows[0][index].ToString();
  index++;
}

Then you can bind the DataTable to gridview, and set AutoGenerateColumn to true.



来源:https://stackoverflow.com/questions/15492589/set-datatable-first-row-as-grid-header

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!