簡體   English   中英

使用C#將數據寫入DataTable中的DataRow

[英]write Data to DataRow in DataTable with C#

我有一個帶有電子郵件的數據表。 在LDAP上,我有Userdata。 現在,我想根據EmailAdress來增加DataTable。

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 ,則必須添加一行與表匹配的列。 這就是為什么如果調用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
}

或者您可以使用kara的答案中建議的Add()方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM