开发者

how to reset rows to newly added column with its default value

I have created an application that shows data in d开发者_如何学JAVAata table. it also provide user interface for adding new column to a data table with its default value.

But problem is, It showing newly created column in data table but default value is not coming. I have to populate data table again to do this which reduces my app performance.
So, how do i overcome this problem...

EDIT:

obj_dataTable.Columns.Add(columnName);

int index = obj_dataTable.Columns.IndexOf(obj_dataTable.Columns[columnName]);

obj_dataTable.Columns[index].DefaultValue = defaultValue;


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜