Default values are assigned when you add a row to the table and the column is not already assigned a value. Therefore, existing rows will not be updated when you change the schema. If you want a generic means of updating a table and applying the default to existing rows then Id create a method to copy the rows from the current data table to a new data table with the extra column in it. Eg:
void doTableStuff()
{
DataTable table1 = makeTable();
table1.Rows.Add(new string[] { "Frederic", "Robert" });
table1 = updateTable(table1);
if (table1.Rows[0]["Sam"] == "Samantha")
{
Console.WriteLine("I Was Right!");
}
else
{
Console.WriteLine("I Was Wrong!");
}
}
DataTable makeTable()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn { ColumnName = "Fred", DataType = typeof(string), DefaultValue = "fred" });
dt.Columns.Add(new DataColumn { ColumnName = "Bob", DataType = typeof(string), DefaultValue = "bob" });
return dt;
}
DataTable updateTable(DataTable oldTable)
{
DataTable newTable = makeTable();
newTable.Columns.Add(new DataColumn { ColumnName = "Sam", DataType = typeof(string), DefaultValue = "Samantha" });
newTable.Merge(oldTable, true, MissingSchemaAction.Add);
return newTable;
}
Sorry, I didn't try running this but you should get the idea. Hope that works.
Cheers
Jonesie
2010-03-03 08:46:23