Saturday, September 3, 2011

How to add columns to DataTables

public DataTable FixupDataTable()

{

   //strip away redundant columns

   DataTable dataTable = this.ProgramsDTO.DataTable;

   List<string> columnNames = new List<string>();

   foreach(DataColumn dataColumn in dataTable.Columns)

      if (dataColumn.Caption != "Foo") columnNames.Add(dataColumn.Caption);

   foreach(string columnName in columnNames)

      dataTable.Columns.Remove(columnName);

   

   //rename the Name column

   dataTable.Columns[0].Caption = "Bar";

   

   //add Open Offerings column and populate it

   dataTable.Columns.Add("Baz", typeof(Int32));

   foreach (DataRow dataRow in dataTable.Rows) dataRow[1] = 88;

   

   //hand back the fixed up DataTable

   this.ProgramsDTO.DataTable = dataTable;

   return this.ProgramsDTO.DataTable;

}

 
 

The above example passes these tests.

Assert.AreEqual(dataTable.Rows.Count,13);

Assert.AreEqual(dataTable.Columns.Count, 2);

Assert.AreEqual(dataTable.Columns[0].Caption, "Bar");

Assert.AreEqual(dataTable.Columns[1].Caption, "Baz");

Assert.AreEqual(dataTable.Rows[0][1], 88);

 
 

Of course, it is nonsensically to have a column with 88 in it a bunch of times over and over. We will need to hydrate the column with actual data. I'm working on that at work now. More soon. Also, forgive my use of foreach. I'll see if I can refactor these away too.

No comments:

Post a Comment