在C#中更改数据表中的列名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10212793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change the Column Name in Datatable in C#
提问by Rushabh Shah
I trying to change the column name of the DataTable but some how I lost the data.
我试图更改 DataTable 的列名,但我如何丢失数据。
foreach (DataRow dr in item)
Ds.Tables[0].ImportRow(dr);
Table.Columns[0].ColumnName = "Barcode";
Table.Columns[1].ColumnName = "Description";
Table.Columns[2].ColumnName = "Price";
Table.Columns[3].ColumnName = "Cost";
Table.Columns[4].ColumnName = "Stock";
Table.Columns[5].ColumnName = "Dept #";
updateDgv.DataSource = Table;
采纳答案by Habib
I have tested your code and it seems to work fine:
我已经测试了你的代码,它似乎工作正常:
DataTable table = new DataTable();
table.Columns.Add("ItemNo", typeof(string));
table.Columns.Add("ItemName", typeof(string));
DataRow dr = table.NewRow();
dr[0] = "1";
dr[1] = "Name1";
table.Rows.Add(dr);
dr = table.NewRow();
dr[0] = "1";
dr[1] = "Name1";
table.Rows.Add(dr);
table.Columns[0].ColumnName = "Item #";
Probably you are trying to access data through column name later in the code and that is where it is failing. You will not loose the data by just renaming the column name. (Also its a not a good practice use special characters in table column names)
Check out the following screen shots from data visualizer
Before Column Rename:
可能您稍后在代码中尝试通过列名访问数据,这就是失败的地方。仅重命名列名不会丢失数据。(在表列名中使用特殊字符也不是一个好习惯)在列重命名之前
查看数据可视化器的以下屏幕截图
:
After Column Rename:
列重命名后:
回答by Steve Wellens
First, the correct code is:
首先,正确的代码是:
DataTable table = new DataTable();
table.Columns.Add("ItemNo", typeof(string));
table.Columns[0].ColumnName = "Item #";
After your code runs, you have a DataTable with one column named Item #.
代码运行后,您将拥有一个 DataTable,其中有一列名为Item #.
There are no rows or data because you didn't add any data. So you didn't lose anything.
没有行或数据,因为您没有添加任何数据。所以你没有失去任何东西。

