locked
update datatable via datarow RRS feed

  • Question

  • Hi List,

    I have a datatable, query through using a foreach in rows, then I update the rows and expect datatable gets updated: Does this work?

    cheers, 

    Arvin

    --------------

    datatable dt = new datatable();

    foreach(DataRow row in dt.Rows)

    {

       row[0] = "new name";

       row[1] = "new text";

      dt.AcceptChanges()

    }

    Does this change the entire of first column and second column of datatable dt into "new name" and "new text"?

    --------------

    Monday, January 13, 2014 12:21 PM

Answers

  •   Yes it does. Move dt.AcceptChanges() to outside of for loop..

      
     DataTable dt = new DataTable();
            dt.Columns.Add("yourcol1", typeof(string));
            dt.Columns.Add("yourcol2", typeof(string));
            dt.Rows.Add(new object[] { "col1", "col2" });
            System.Console.WriteLine("Before For/change");
    
            foreach (DataRow objRow in dt.Rows)
            {
                Console.WriteLine(" {0} {1}", objRow[0], objRow[1]);
                foreach (DataRow row in dt.Rows)
                {
                    row[0] = "new name";
                    row[1] = "new text";
                }
                dt.AcceptChanges();
                System.Console.WriteLine("After For/change");
                foreach (DataRow row in dt.Rows)
                {
                    Console.WriteLine(" {0} {1}", row[0], row[1]);
    
               }

    • Marked as answer by azolfaghari Monday, January 13, 2014 2:19 PM
    Monday, January 13, 2014 1:50 PM

All replies

  •   Yes it does. Move dt.AcceptChanges() to outside of for loop..

      
     DataTable dt = new DataTable();
            dt.Columns.Add("yourcol1", typeof(string));
            dt.Columns.Add("yourcol2", typeof(string));
            dt.Rows.Add(new object[] { "col1", "col2" });
            System.Console.WriteLine("Before For/change");
    
            foreach (DataRow objRow in dt.Rows)
            {
                Console.WriteLine(" {0} {1}", objRow[0], objRow[1]);
                foreach (DataRow row in dt.Rows)
                {
                    row[0] = "new name";
                    row[1] = "new text";
                }
                dt.AcceptChanges();
                System.Console.WriteLine("After For/change");
                foreach (DataRow row in dt.Rows)
                {
                    Console.WriteLine(" {0} {1}", row[0], row[1]);
    
               }

    • Marked as answer by azolfaghari Monday, January 13, 2014 2:19 PM
    Monday, January 13, 2014 1:50 PM
  • Hi

    When you know how to code then instead of asking us why don't you check it out yourself.?

    Monday, January 13, 2014 2:10 PM
  • or maybe I was away from visual studio
    Monday, January 13, 2014 2:19 PM
  • thanks
    Monday, January 13, 2014 2:19 PM