C#如何更改DataTable中的数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1666087/
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
C# how to change data in DataTable?
提问by fazzy
I'v got some problem, I use DataTable to store my data in dataGridView. Data was inputed like this:
我遇到了一些问题,我使用 DataTable 将我的数据存储在 dataGridView 中。数据是这样输入的:
dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("par", typeof(string));
dt.Columns.Add("max", typeof(int));
dt.Columns.Add("now", typeof(int));
dt.Rows.Add(new object[] { id++,i + " " + j++, strarr[0], strarr[1] }); // ... etc etc
dataGridView1.DataSource = dt;
now I want to do some changes, I use code:
现在我想做一些改变,我使用代码:
dt.Rows[1].ItemArray[3] = "VALUE";
When I debug, ItemArray represents the row I want to, so its okey, but still I can't do any changes, whats wrong ? How to update DataTable ??? I'm googling and nothing :(
当我调试时,ItemArray 代表我想要的行,所以没关系,但我仍然无法做任何更改,怎么了?如何更新数据表???我在谷歌上搜索,什么都没有:(
回答by manji
dt.Rows[1].ItemArray
gives you a copy of item arrays. When you modify it, you're not modifying the original.
dt.Rows[1].ItemArray
为您提供项目数组的副本。当您修改它时,您并没有修改原始文件。
You can simply do this:
你可以简单地这样做:
dt.Rows[1][3] = "Value";
ItemArray property is used when you want to modify all row values.
当您要修改所有行值时,将使用 ItemArray 属性。
ex.:
前任。:
dt.Rows[1].ItemArray = newItemArray;
回答by Yannick Compernol
Try the SetField method:
尝试 SetField 方法:
table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);
table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);
This should get the job done and is a bit "cleaner" than using Rows[i][j].
这应该可以完成工作,并且比使用 Rows[i][j] 更“干净”一些。
回答by gons
You should probably set the property dt.Columns["columnName"].ReadOnly = false;
before.
您可能应该dt.Columns["columnName"].ReadOnly = false;
之前设置该属性。