virusisfound 0 Junior Poster

how to update datagridview in C# windows application.

I want to update the rows in datagridview. I have 1textbox, 1gridview, and button.

Before saving the data I want to make additions of textbox value and datagrid value. if i enter 20 value in textbox. the value should be add in the data present in datagridview. I have done some code but the code updates all rows with last row value. How to update every line.

The Code is here :

This code make the addition of textbox and datagridview column.

try
            {
                double w1;
                w1 = 0;

                for (int i = 0; i <dataGridView1.Rows.Count; i++)
                {
                    w1 = Convert.ToDouble(dataGridView1["el", i].Value) + Convert.ToDouble(cloudTextBox1.Text);
                    dataGridView1["elsid", i].Value = w1.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

this code is to update the gridview.

private void btn_el_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult result = MessageBox.Show("Do You Want To Save Service Record", "Save Service Record", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (result == DialogResult.Yes)
                {
                    cn = new SqlConnection(s);
                    cn.Open();

                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        string s12 = "update leave set el=@el";
                        SqlCommand cmd1 = new SqlCommand(s12, cn);
                        cmd1.Parameters.AddWithValue("@el", row.Cells["elsid"].Value.ToString());
                        cmd1.ExecuteNonQuery();
                    }
                }
                else if (result == DialogResult.No)
                {
                    MessageBox.Show("Data Not Save", "Save Data", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Service Record Save Successfully", "Save Service Record", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.