How to add a new row to c# DataTable in 1 line of code?

Viewed 85008

Is it possible to add a new row to a datatable in c# with just 1 line of code? I'm just dummying up some data for a test and it seems pretty slow to have to write something like this:

DataTable dt= new DataTable("results");
DataRow dr1 = dt.NewRow();
dr1[0] = "Sydney";
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = "Perth";
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3[0] = "Darwin";
dt.Rows.Add(dr3);

I was assuming you could do something like the code below, but I can't find the correct syntax.

dt.Rows.Add(dt.NewRow()[0]{"Sydney"});
dt.Rows.Add(dt.NewRow()[0]{"Perth"});
dt.Rows.Add(dt.NewRow()[0]{"Darwin"});

And yes I know in the time I've taken to write this question I could have finished coding it the long way instead of procrastinating about it :)

Thanks!

5 Answers

DataTable dtStudent = new DataTable();

//Add new column
dtStudent.Columns.AddRange (
new DataColumn[] {
new DataColumn("SlNo", typeof(int)), 
new DataColumn("RollNumber", typeof(string)),
new DataColumn("DateOfJoin", typeof(DateTime)),
new DataColumn("Place", typeof(string)),
new DataColumn("Course", typeof(string)),
new DataColumn("Remark", typeof(string))
}
);
// Add value to the related column
dtStudent.Rows.Add(1, "10001", DateTime.Now, "Bhubaneswar", "MCA", "Good");

To quickly create a new DataTable with some data you can do all in one line:

DataTable testData = new DataTable( "TestData" ) {
    Columns = { "TestColumn1", "TestColumn2" },
    Rows = {
        { "Row1Col1Val", "Row1Col2Val"},
        { "Row2Col1Val", "Row2Col2Val"}
    }
};
Related