beari7
beari7

Reputation: 105

write Data to DataRow in DataTable with C#

I have a DataTables with Emails. Over the LDAP I have the Userdata. Now Id like to Increase the DataTable depending upon the EmailAdress.

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
}

how can I insert the new Data from LDAP to the new Column?

Thanks

Upvotes: 2

Views: 9034

Answers (3)

kara
kara

Reputation: 3455

If you add a row to a DataTable you have to add a row which columns match you table. This is why you get back a row if you call DataTable.Add().

Here an example how to add new rows:

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();
    }

}

Upvotes: 2

Lajos Arpad
Lajos Arpad

Reputation: 77053

You can do it by using the NewRow method:

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
}

Or you can use the Add() method, as suggested in kara's answer.

Upvotes: 1

Nitin S
Nitin S

Reputation: 7600

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);
}

Upvotes: 1

Related Questions