How to add New Column with Value to the Existing DataTable?

257,930

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;
Share:
257,930
thevan
Author by

thevan

Software Engineering Senior Analyst at Accenture Solutions Private Limited, Chennai, India. Interested in ASP.Net, MVC, Web API, WCF, Web Services, ADO.Net, C#.Net, VB.Net, Entity Framework, MS SQLServer, Angular.js, JavaScript, JQuery, Ajax, HTML and CSS

Updated on July 12, 2020

Comments

  • thevan
    thevan almost 4 years

    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?

  • Ahmad Mageed
    Ahmad Mageed almost 13 years
    +1 I take that back. Setting up the column with the DefaultValue then adding it to the Columns collection has the desired effect of being applied to all existing rows. However, adding it to Columns and then setting the DefaultValue doesn't produce the same result (in which case it only works on newly added rows and not existing ones).
  • Kiquenet
    Kiquenet about 7 years
    And using DefaultValue for new System.Data.DataColumn ?
  • Tim Schmelter
    Tim Schmelter about 7 years
    @Kiquenet: Why should i use that? Wouldn't it be a duplicate to Keith's answer then? Using DefaultValue is just a different approach. This one works too and isn't less efficient just a little bit less concise. It also has no drawbacks, you dont need to remember if you can add the column before you apply the defaultvalue. Also, if you only want this value once when you add the column to the table, you have to remove the DefaultValue again.
  • Pikachu620
    Pikachu620 about 6 years
    Didn't the OP just say WITHOUT USING FOR LOOP!?
  • Tim Schmelter
    Tim Schmelter almost 6 years
    @Pikachu620: well, the for-loop is just hidden in the framework in the accepted answer. Both approaches are same efficient, chose whatever is more readable or what you remember when you need it :)
  • Tim Schmelter
    Tim Schmelter almost 6 years
    @MitchWheat: already commented. I keep my answer because that's what most people will remember when they actually need it and there's nothing bad in using this approach. Using the DefaultValue is elegant, but you have to remember the order when you have to use it. It's also using a for-loop by the way
  • Mitch Wheat
    Mitch Wheat almost 6 years
    except it's more long winded and less obvious than the accepted answer with 111 upvotes!
  • Tim Schmelter
    Tim Schmelter almost 6 years
    @MitchWheat: the whole "magic" of my answer is: foreach (DataRow row in tbl.Rows) row["NewColumn"] = "You DropDownList value"; That's neither long winded nor complicated
  • Tim Schmelter
    Tim Schmelter almost 6 years
    @MitchWheat: Precisely. Not complicated at all. It's the first thing that comes to your mind when you want to add a column and add the same value into every record. And it's a good approach because you always have to use a loop anyway, either hidden or explicit. Setting the DefaultValue is more dangerous, someone might decide later that he could move this line to the initialization part of the DataTable, then this doesn't work anymore.
  • Mitch Wheat
    Mitch Wheat almost 6 years
    I guess we'll have to agree that one answer got 111 votes and yours got 11. I suppose that speaks for itself.
  • Tim Schmelter
    Tim Schmelter almost 6 years
    @MitchWheat: That speaks for the fact that people think that the DefaultValue approach is more efficient because there is no loop which isn't true. I like explicit and clear code, 111 others dont like. That's opinion based. DefaultValue is more elegant but also might break easier in later refactoring.
  • Mitch Wheat
    Mitch Wheat almost 6 years
    It has nothing to do with " that people think that the DefaultValue approach is more efficient because there is no loop which is't true", it's all about the clarity. Your statement is also "... opinion based. " Anyway I'm sure you need the 120 rep!! :)
  • Tim Schmelter
    Tim Schmelter almost 6 years
    @MitchWheat: Clarity is subjective too. DefaultValue does the job but it's actually doing more than OP has asked for. It was never the reuquirement that the DropDownList value should be added as default value now and in future whenever a new row is added to this table. The requirement was to add it 10 times because now this table contains 10 rows. So you should clear the DefaultValue property afterwards.
  • KeitelDOG
    KeitelDOG about 4 years
    Thanks, that helped a friend of mine
  • paraJdox1
    paraJdox1 over 3 years
    why table does not exits in the current context?