79

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?

thevan
  • 10,052
  • 53
  • 137
  • 202
  • @CheckRaise: It would take more time to complete the loop, if the DataTable contains more records. – thevan Jun 21 '11 at 14:36

3 Answers3

155

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);
Keith Walton
  • 5,211
  • 6
  • 39
  • 53
  • 14
    +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). – Ahmad Mageed Jun 21 '11 at 14:38
  • why table does not exits in the current context? – paraJdox1 Nov 18 '20 at 06:10
  • must add this : DataRow row = table.NewRow(); table.Rows.Add(row); – udorb b Oct 11 '22 at 08:31
19

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;
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • And using `DefaultValue` for `new System.Data.DataColumn` ? – Kiquenet Mar 08 '17 at 09:26
  • @Kiquenet: Why should i use that? Wouldn't it be a duplicate to [Keith's answer](http://stackoverflow.com/a/6427038/284240) 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. – Tim Schmelter Mar 08 '17 at 09:31
  • 2
    Didn't the OP just say **WITHOUT USING FOR LOOP**!? – Pikachu620 Apr 20 '18 at 02:07
  • @Pikachu620: well, the for-loop is just [hidden in the framework](https://referencesource.microsoft.com/#System.Data/System/Data/DataColumnCollection.cs,fdb021b4f011e7b8,references) in the accepted answer. Both approaches are same efficient, chose whatever is more readable or what you remember when you need it :) – Tim Schmelter May 29 '18 at 07:55
  • @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 – Tim Schmelter May 29 '18 at 07:58
  • except it's more long winded and less obvious than the accepted answer with 111 upvotes! – Mitch Wheat May 29 '18 at 07:59
  • @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 May 29 '18 at 08:00
  • @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. – Tim Schmelter May 29 '18 at 08:03
  • I guess we'll have to agree that one answer got 111 votes and yours got 11. I suppose that speaks for itself. – Mitch Wheat May 29 '18 at 08:05
  • @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. – Tim Schmelter May 29 '18 at 08:07
  • 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!! :) – Mitch Wheat May 29 '18 at 08:11
  • @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. – Tim Schmelter May 29 '18 at 08:14
  • Thanks, that helped a friend of mine – KeitelDOG Mar 02 '20 at 20:43
-2
//Data Table

 protected DataTable tblDynamic
        {
            get
            {
                return (DataTable)ViewState["tblDynamic"];
            }
            set
            {
                ViewState["tblDynamic"] = value;
            }
        }
//DynamicReport_GetUserType() function for getting data from DB


System.Data.DataSet ds = manage.DynamicReport_GetUserType();
                tblDynamic = ds.Tables[13];

//Add Column as "TypeName"

                tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));

//fill column data against ds.Tables[13]


                for (int i = 0; i < tblDynamic.Rows.Count; i++)
                {

                    if (tblDynamic.Rows[i]["Type"].ToString()=="A")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Apple";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "B")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Ball";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "C")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Cat";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "D")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Dog;
                    }
                }
Valerica
  • 1,618
  • 1
  • 13
  • 20