How to add New Column with Value to the Existing DataTable?
I have One DataTable with 5 Columns and 10 Rows. Now I want to add one New Column to the DataTable and I want to assign DropDownList value to the New Column. So the DropDownList value should be added 10 times to the New Column. How to do this? Note: Without using FOR LOOP.
For Example: My Existing DataTable is like this.
ID Value
----- -------
1 100
2 150
Now I want to add one New Column "CourseID" to this DataTable. I have One DropDownList. Its selected value is 1. So My Existing Table should be like below:
ID Value CourseID
----- ------ ----------
1 100 1
2 150 1
How to do this?
Solution 1:
Without For loop:
Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))
newColumn.DefaultValue = "Your DropDownList value"
table.Columns.Add(newColumn)
C#:
System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);
Solution 2:
Add the column and update all rows in the DataTable
, for example:
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Name", typeof(string)));
for (Int32 i = 1; i <= 10; i++) {
DataRow row = tbl.NewRow();
row["ID"] = i;
row["Name"] = i + ". row";
tbl.Rows.Add(row);
}
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
tbl.Columns.Add(newCol);
foreach (DataRow row in tbl.Rows) {
row["NewColumn"] = "You DropDownList value";
}
//if you don't want to allow null-values'
newCol.AllowDBNull = false;