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

3 Answers

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

}
2

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest