PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 21, 2022

[FIXED] How to insert row at any desired position in datatable?

 November 21, 2022     .net, asp.net, c#, visual-studio, visual-studio-2008     No comments   

Issue

I have a datatable which contains 10 rows. I now need to insert 11th row at the position specified by some conditions.

I have tried the InsertAt method but that gives the error of "this row already belongs to another table".

I cannot use ImportRow method as that simply import the rows into datatable and inserts the row at the end of the existing rows.

What should i do? Kindly help!

Thanks

UPDATED CODE

        int iCount = 0;
        foreach (DataRow dr in dtWithBundle.Rows)
        {
            DataRow drClone = dtOppClone.NewRow();
            drClone.ItemArray = dr.ItemArray;
            dtOpps.Rows.InsertAt(drClone, iIndex + iCount);
            //dtOpps.ImportRow(drClone);
            //dtOpps.Rows.Add(drClone.ItemArray); // Commented on Aug-4 2011 1700HRS
            iCount++;
            dtOpps.AcceptChanges();
        }

Solution

Try this. I think the error you are getting is bcz you are not creating NewRow.

    DataTable dt = new DataTable();
    dt.Columns.Add("Name", typeof(string));

    DataRow dr;
    dr = dt.NewRow();
    dr[0] = "A";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0] = "C";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0] = "B";
    dt.Rows.InsertAt(dr,1);

    foreach (DataRow d in dt.Rows)
    {
        Console.WriteLine(d[0].ToString());

    }

    Console.Read();


Answered By - Asdfg
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing