Add/Remove Columns of a DataTable Dynamically/RunTime

if u want to add some of the columns in ur existing datatable in runtime then the below code will be very usefull....
let ur datatable columns will be (ID,Name) before adding the columns into the datattable(dttable)
and now u want add two more columns into the datatable(dttable) then below will the code for this
VB.NET Code
Dim CreatedDate As DataColumn
Dim Address As DataColumn

CreatedDate = New DataColumn("CreatedDate", System.Type.GetType("System.DateTime"))
'if u want to set the same values for all the rows then write the below code other 'wise just remove the below line
CreatedDate.DefaultValue = Now.Date 'set the default value for all the rows
If dttable.Columns.Contains("CreatedDate") = True Then
dttable.Columns.RemoveAt("CreatedDate")
dtTable.Columns.Add(CreatedDate)
Else
dtTable.Columns.Add(CreatedDate)
End If

Address = New DataColumn("Address", System.Type.GetType("System.String"))
Address.DefaultValue = "India" 'set the default value for all the rows
If dtTable.Columns.Contains("Address") = True Then
dtTable.Columns.Remove("Address")
dtTable.Columns.Add(Address)
Else
dtTable.Columns.Add(Address)
End If
Now ur datatable(dttable) columns will be (ID,Name,CreatedDate,Address)

C#.NET Code
DataColumn CreatedDate = null;
DataColumn Address = null;

CreatedDate = new DataColumn("CreatedDate", System.Type.GetType("System.DateTime"));
CreatedDate.DefaultValue = DateAndTime.Now.Date;
if (dttable.Columns.Contains("CreatedDate") == true) {
dttable.Columns.RemoveAt("CreatedDate");
dtTable.Columns.Add(CreatedDate);
} else {
dtTable.Columns.Add(CreatedDate);
}

Address = new DataColumn("Address", System.Type.GetType("System.String"));
//if u want to set the same values for all the rows then write the below code other //wise just remove the below line
Address.DefaultValue = "India"; 'set the default value for all the rows
if (dtTable.Columns.Contains("Address") == true) {
dtTable.Columns.Remove("Address");
dtTable.Columns.Add(Address);
} else {
dtTable.Columns.Add(Address);
}

No comments:

Post a Comment