C# - 如何从数据表中获取标题行并将其垂直排列在列中?

时间:2016-06-17 04:14:58

标签: c# visual-studio visual-studio-2013 datagridview datatable

如何从datatable转换此datagridview enter image description here

进入这个 enter image description here

现在是我的代码。任何建议,评论或示例代码都非常感谢。谢谢。

            DataSet result = excelReader.AsDataSet();

            excelReader.Close();

            if (result != null)
            {
                DataTable dataTable = result.Tables[0];
                List<string> headers = new List<string>();
                foreach (DataColumn col in dataTable.Columns)
                {
                    headers.Add(col.ColumnName);
                }
                dataGridView1.DataSource = dataTable;
            }

3 个答案:

答案 0 :(得分:5)

尝试

string[] columnNames = dt.Columns.Cast<DataColumn>()
                                 .Select(x => x.ColumnName)
                                 .ToArray();  
dataGridView1.DataSource = columnNames;

dataGridView1.DataSource = dt.Columns.Cast<DataColumn>()
                                 .Select(x => x.ColumnName)
                                 .ToArray(); 

答案 1 :(得分:0)

只需将Header设置为可见:

DataGridView.ColumnHeaderVisible = true;

这对我有用。

答案 2 :(得分:0)

System.Data.DataTable dt = GridDataSource.Tables[0];
            
foreach (System.Data.DataColumn col in dt.Columns)
{
   cmbSelectSearchBy.Items.Add(col.ColumnName);
}
cmbSelectSearchBy.Text = "Select Column";