使用c#将值分配给Datatable中的特定列

Anu*_*uya 4 c#

我创建了一个数据表并添加了许多列.

当数据表为空时,我想为特定列分配值.

就像在datatable中查找列名并为其赋值...是否可能?谢谢

        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));
Run Code Online (Sandbox Code Playgroud)

有一种情况,我只能获得必须分配给上述数据表中的列"FQ_Answer_1"的值.在这种情况下,我想单独为该列赋值,并将空字符串""传递给其他列.有可能?

Hab*_*bib 7

如果现有数据表中包含数据,则必须遍历数据表行并为每列设置值

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
}
Run Code Online (Sandbox Code Playgroud)

要查找特定列,您可以执行以下操作:

    DataColumn dc = dt.Columns.Cast<DataColumn>().Where(r => r.ColumnName == "yourname").FirstOrDefault();
   //Or simpler 
    DataColumn dc2 = dt.Columns["yourcol"];
Run Code Online (Sandbox Code Playgroud)

编辑:对于新行:

DataRow dr = dt_FAQ.NewRow();
dr["FQ_Answer_1"] = "some value";
dt_FAQ.Rows.Add(dr);
Run Code Online (Sandbox Code Playgroud)

这将为列创建一个具有"某个值"的新行,FQ_Answer1其余所有列将具有string.Empty默认值.

您可以查看其他列,例如:

string test = dt_FAQ.Rows[0]["FQ_Question_1"].ToString();
Run Code Online (Sandbox Code Playgroud)

这里test将包含一个空字符串.