使用 c# 为数据表中的特定列赋值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11241320/
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
Assign value to a specific Column in Datatable using c#
提问by Anuya
I have created a datatable and added many columns to it.
我创建了一个数据表并向其中添加了许多列。
When the datatable is empty, i want to assign a value to a specific column.
当数据表为空时,我想为特定列分配一个值。
Like finding the column name in datatable and assign value to it... Is it possible ? Thanks
就像在数据表中查找列名并为其赋值......这可能吗?谢谢
dt_FAQ.Columns.Add("FQ_Question_1", typeof(string));
dt_FAQ.Columns.Add("FQ_Answer_1", typeof(string));
dt_FAQ.Columns.Add("FQ_Question_2", typeof(string));
dt_FAQ.Columns.Add("FQ_Answer_2", typeof(string));
dt_FAQ.Columns.Add("FQ_Question_3", typeof(string));
dt_FAQ.Columns.Add("FQ_Answer_3", typeof(string));
dt_FAQ.Columns.Add("FQ_Question_4", typeof(string));
dt_FAQ.Columns.Add("FQ_Answer_4", typeof(string));
dt_FAQ.Columns.Add("FQ_Question_5", typeof(string));
dt_FAQ.Columns.Add("FQ_Answer_5", typeof(string));
There is a scenario where i would get only the value that has to be assigned to column "FQ_Answer_1" in the above datatable. In that case, i want to assgn value to that column alone and pass empty string "" to other columns. Possible ?
有一种情况,我只会获得必须分配给上述数据表中“FQ_Answer_1”列的值。在这种情况下,我想将值单独分配给该列并将空字符串 "" 传递给其他列。可能的 ?
回答by Nikhil Agrawal
How about
怎么样
DataRow dr = mydatatable.NewRow();
dr[0] = 1; // Assuming that first column is int type
dr[0] = "someothervalue"; //Assuming that second column is string type
..
..
..
.. // Repeat for other columns.
mydatatable.AddRow(dr);
回答by Habib
In case of your existing datatable with data inside, you have to iterate through the datatable rows and set values to each column
如果您现有的数据表中包含数据,则必须遍历数据表行并将值设置为每列
foreach(DataRow dr in dt_FAQ.Rows)
{
dr["FQ_Answer_1"] = "your value";
dr["FQ_Question_1"] = string.Empty;
dr["FQ_Question_2"] = string.Empty;
//.... for all the columns
}
To find a particular column you can do:
要查找特定列,您可以执行以下操作:
DataColumn dc = dt.Columns.Cast<DataColumn>().Where(r => r.ColumnName == "yourname").FirstOrDefault();
//Or simpler
DataColumn dc2 = dt.Columns["yourcol"];
EDIT: For new Row:
编辑:对于新行:
DataRow dr = dt_FAQ.NewRow();
dr["FQ_Answer_1"] = "some value";
dt_FAQ.Rows.Add(dr);
This will create a new row with "some value" for column FQ_Answer1, all the other remaining columns will have string.Emptyas default value.
这将为 column 创建一个具有“某个值”的新行FQ_Answer1,所有其他剩余的列将具有string.Empty默认值。
You can check other columns like:
您可以检查其他列,例如:
string test = dt_FAQ.Rows[0]["FQ_Question_1"].ToString();
Here test will contain an empty string.
这里 test 将包含一个空字符串。

