Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

datatable

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!

like image 322
JumpingJezza Avatar asked Sep 20 '10 02:09

JumpingJezza


People also ask

How do you insert a new row?

To insert a single row: Right-click the whole row above which you want to insert the new row, and then select Insert Rows. To insert multiple rows: Select the same number of rows above which you want to add new ones. Right-click the selection, and then select Insert Rows.

How do I add a new row to a row 30?

Use Insert to add a row To insert a row, pick a cell or row that's not the header row, and right-click. To insert a column, pick any cell in the table and right-click. Point to Insert, and pick Table Rows Above to insert a new row, or Table Columns to the Left to insert a new column.


1 Answers

Yes, you can do the following:

dt.Rows.Add("Sydney");
like image 128
Jeff Ogata Avatar answered Oct 02 '22 20:10

Jeff Ogata