title: How to Update DataTable in C# without For Each Loop?
body: <p>I'm trying to run loop for each row in my data table but its giving me error as I can't modify a collection in for each loop ... what else can i do to update table?</p>
  
  <p>I am trying to remove duplicate entries w.r.t single column that is <strong>appliance name</strong> and if such selection is made based on duplicate appliance name then simply update the old <strong>quantity</strong>. </p>
  
  <p>Here is the code:</p>
  
  <pre><code>protected void Page_Load(object sender, EventArgs e)
  {
      if (!IsPostBack)
      {
          dt = new DataTable();
          dt.Columns.Add("Appliance Name", typeof(string));
          dt.Columns.Add("Quantity", typeof(int));
          dt.Columns.Add("Day Time(Hrs)", typeof(int));
          dt.Columns.Add("Backup Time(Hrs)", typeof(int));
          // dt.Rows.Add("Sana", 5, 4, 3);
          Session["MyDataTable"] = dt;
      }
  }
  
  protected void BtnAddNext_Click(object sender, EventArgs e)
  {
      DataTable dtab = (DataTable)Session["MyDataTable"];
  
      if (dtab.Rows.Count != 0)
      {
          foreach (DataRow r in dtab.Rows)
          {
              if (Convert.ToString(r["Appliance Name"]) == DDLAppName.Text)
              {
                  int temp = Convert.ToInt32(r["Quantity"]);
                  r["Quantity"] = Convert.ToInt32(QtyTB.Text) + temp;
              }
              else
              {
                  dtab.Rows.Add(DDLAppName.SelectedValue, Convert.ToInt32(QtyTB.Text), Convert.ToInt32(DayTymTB.Text), Convert.ToInt32(BackUpTymTB.Text));
              }
          }
      }
      else if (dtab.Rows.Count == 0)
      {
          dtab.Rows.Add(DDLAppName.SelectedValue, Convert.ToInt32(QtyTB.Text), Convert.ToInt32(DayTymTB.Text), Convert.ToInt32(BackUpTymTB.Text));
      }
  
      //dtab = dtab.DefaultView.ToTable(true, "Appliance Name", "Quantity", "Day Time(Hrs)", "Backup Time(Hrs)");
      AllItems.DataSource = dtab;
      AllItems.DataBind();
      AllItems.Visible = true;
  }
  </code></pre>