用C#向DataTable中的DataRow写入数据

write Data to DataRow in DataTable with C#

我有一个带电子邮件的数据表。通过 LDAP 我有用户数据。现在我想根据电子邮件地址增加数据表。

myDataTable.Columns.Add(new DataColumn("LDAP_Data"));

foreach(DataRow row in modiTable.Rows)
{
    string myLDAPData = DoLDAPAction(row.Field<string>("EMAIL"));

    //how to insert to myDataTable > LDAP_Data
}

如何将 LDAP 中的新数据插入到新列中?

谢谢

如果您向 DataTable 添加一行,则必须添加一个列与您匹配的行 table。这就是为什么你调用 DataTable.Add().

会返回一行的原因

这里是一个如何添加新行的例子:

static void Main(string[] args)
{
    DataTable dt = new DataTable(); // Create a example-DataTable
    dt.Columns.Add(new DataColumn() { ColumnName = "Name", DataType = typeof(string) }); // Add some columns
    dt.Columns.Add(new DataColumn() { ColumnName = "Id", DataType = typeof(int) });

    // Let's fill the table with some rows
    for (int i = 0; i < 20; i++) // Add 20 Rows
    {
        DataRow row = dt.Rows.Add(); // Generate a row
        row["Id"] = i; // Fill in some data to the row. We can access the columns which we added.
        row["Name"] = i.ToString();
    }

    // Let's see what we got.
    for (int i = 0; i < dt.Columns.Count; i++) // Loop through all columns
    {
        Console.Write(dt.Columns[i].ColumnName + ";"); // Write the ColunName to the console with a ';' a seperator.
    }
    Console.WriteLine();

    foreach (DataRow r in dt.Rows) // Generic looping through DataTable
    {
        for (int i = 0; i < dt.Columns.Count; i++) // Loop through all columns
        {
            Console.Write(r[i] + ";");
        }
        Console.WriteLine();
    }

}
myDataTable.Columns.Add(new DataColumn("LDAP_Data"));

foreach(DataRow row in modiTable.Rows)
{
    string myLDAPData = DoLDAPAction(row.Field<string>("EMAIL"));

    var row = myDataTable.NewRow()
    row["LDAP_Data"] = YOUR_DATA;
    myDataTable.Rows.Add(row);
}

您可以使用NewRow方法来完成:

foreach(DataRow row in modiTable.Rows)
{
    string myLDAPData = DoLDAPAction(row.Field<string>("EMAIL"));

    DataRow row = modiTable.NewRow();
    row["EMAIL"] = myLDAPData;
    //You might want to specify other values as well
}

或者您可以使用 Add() 方法,如 kara 的回答中所建议的那样。