简体   繁体   中英

How to Update DataTable in C# without For Each Loop?

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?

I am trying to remove duplicate entries wrt single column that is appliance name and if such selection is made based on duplicate appliance name then simply update the old quantity .

Here is the 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;
}

Simply try using for loop instead of foreach like this:

for (int rowIndex = 0; rowIndex < dtab.Rows.Count; rowIndex++)
{
    DataRow r = dtab.Rows[rowIndex];
    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));
    }
}

EDIT 1: The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop. (From MSDN )

Edit 2 If you wanna add rows in your foreach loop, do as follows:

    DataRow[] dataRows = new DataRow[dt.Rows.Count];
    dt.Rows.CopyTo(dataRows, 0);
    foreach (DataRow r in dataRows)
    {
              ...
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM