tags:

views:

84

answers:

3

Hi

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!

+7  A: 

Yes, you can do the following:

dt.Rows.Add("Sydney");
adrift
Don't need to create an array. It already accept a `params` array argument.
Pierre-Alain Vigeant
@Pierre-Alain Vigeant - ahah I see! I can just go `dt.Rows.Add("Sydney");`
JumpingJezza
+1  A: 

If you're doing this for Unit Tests, why not just use a helper method, either in some static class, or better yet a test base class?

I have all test classes inheriting from a TestBase class, where i can add stuff to help out all the tests.

e.g

[TestClass]
public class TestBase
{
   protected void AddMockDataRow(DataTable dt)
   {
      DataRow dr = dt.NewRow();
      dr[0] = "Sydney"; // or you could generate some random string.
      dt.Rows.Add(dr);
   }
}

Then in your test class:

[TestClass]
public class SomeTest : TestBase
{
    [TestMethod]
    public void Ensure_Something_Meets_Some_Condition()
    {
       // Arrange.
       DataTable dt = new DataTable("results");

       // Act.
       AddMockDataRow(dt);

       // Assert.
       Assert.IsTrue(someCondition);
    }
}

The goal here is to keep your test code minimal and reduce redundant code (not to be DRY).

HTH

RPM1984
Ah now if I was doing it properly and using Unit Tests this would be the way to go.
JumpingJezza
@JumpingJezza - i read the statement "I'm just dummying up some data for a test", as you WERE creating unit tests.
RPM1984
@RPM1984 - sorry for misleading you but I'm just pulling some code out of the main project and creating a new project to test some specific functionality, rather than the proper way of creating unit tests. :)
JumpingJezza
+1  A: 

Another way would be to make a helper function to do it:

DataTable MakeDataTable(String name, String contents)
{
  DataTable dt = new DataTable(name);
  foreach (string val in contents.Split(","))
  {
    DataRow dr = dt.NewRow();
    dr[0] = val;
    dt.Rows.Add(dr);
  }
  return dt;
}

MakeDataTable("results","Sydney,Perth,Darwin");
Chris