7/10/2014

Increment the value of Qty if row with the same data already exists in DataGridView

Increment the value of Qty if row with the same data already exists in DataGridView
Increment the value of Qty if row with the same data already exists in DataGridView


private void btn_Add_Click(object sender, EventArgs e)  
     {  
       //Boolean value to check if the DataGridView has the same value.  
       bool Found = false;  
       double total = Convert.ToDouble(txt_Price.Text) * 1;  
       if (dataGridView1.Rows.Count > 0)  
       {  
         //Check if the product Name exists with the same Price  
         foreach (DataGridViewRow row in dataGridView1.Rows)  
         {  
           if (Convert.ToString(row.Cells[0].Value) == txt_Name.Text && Convert.ToString(row.Cells[2].Value) == txt_Price.Text)  
           {  
             //Update the Quantity of the found row  
             row.Cells[1].Value = Convert.ToString(1 + Convert.ToInt16(row.Cells[1].Value));  
             row.Cells[3].Value = Convert.ToDouble(row.Cells[1].Value) * Convert.ToDouble(row.Cells[2].Value);  
             Found = true;  
           }  
         }  
         if (!Found)  
         {  
           //Add the row to DataGridView if data not present  
           dataGridView1.Rows.Add( txt_Name.Text,1, txt_Price.Text,total);  
         }  
       }  
       else  
       {  
         //Add the first row to DataGridView if there is no row  
         dataGridView1.Rows.Add( txt_Name.Text, 1, txt_Price.Text,total);  
       }  
     }