locked
Insert New Column into Datatable RRS feed

  • Question

  • User-2050663300 posted

    Here, I am trying to insert New column named "Rank" into the Datatable. It inserts Column name "Rank" and even inserting count numbers but

    for i.e. if 10 records are present in datatable then it is inserting Rank value from the 11 number index...
    dsCollege is datatable... Count is total number of records...

    DataColumn dcRank = new DataColumn();
            dcRank.DataType = typeof(Int32);
            dcRank.ColumnName = "Rank";
    
            dsCollege.Columns.Add(dcRank);
    
            for (int i = 0; i <= count; i++)
            {
                DataRow dr = dsCollege.NewRow();
                dr["Rank"] = i.ToString();
                dsCollege.Rows.Add(dr);
            }
    


    Friday, January 25, 2013 7:32 AM

Answers

  • User614805505 posted

    Hi,

    According to your requirement, you cannot have "NewRow()" and it must be update to existing row.

    DataRow dr = dsCollege.NewRow();

    Please try this instead.

    dsCollege.Rows[i].SetField("Rank", i.ToString());

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, January 26, 2013 5:03 AM

All replies

  • User614805505 posted

    Hi,

    You might want to describe your issue clearly. :)

    Friday, January 25, 2013 7:55 AM
  • User223678428 posted

    Based solely on your post it sounds like it's working.  You need to have a question.  Tongue Out

    Friday, January 25, 2013 1:44 PM
  • User-2050663300 posted

    I have one datatable...

    like...

    Name          Address               Number
    Jeeten         Vadodara            123456789
    Deep          Vadodara             1236547956

    Now, I am adding one more column named "Rank" in this datatable by using code as u can see in main post... Then im getting result,

    Name          Address               Number            Rank
    Jeeten         Vadodara            123456789
    Deep          Vadodara             1236547956
                                                                            1

                                                                            2

    But, I want it as,

    Name          Address               Number               Rank
    Jeeten         Vadodara            123456789               1
    Deep          Vadodara             1236547956             2

    Friday, January 25, 2013 10:56 PM
  • User614805505 posted

    Hi,

    According to your requirement, you cannot have "NewRow()" and it must be update to existing row.

    DataRow dr = dsCollege.NewRow();

    Please try this instead.

    dsCollege.Rows[i].SetField("Rank", i.ToString());

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, January 26, 2013 5:03 AM