mohamed ahmed

mohamed ahmed

  • 1.7k
  • 43
  • 2.6k

How to update cell value at Datagridview to the database . c# ?

Sep 22 2022 7:00 PM

i have adatagridview showinfg table content ,when i am trying to change a cell value at column directly from the datagridview 

the update change all  rows for the columns  to the new value.

ex:- if checked row 1 column "CanShow "  to "true" . all rows for the column "CanShow "aslo change to "true "

i just want to update only the cells i changed

here is my code :-

private void button4_Click(object sender, EventArgs e)
{
    try
    {


        if (TXT_ID.Text != "")
        {
            foreach (DataGridViewRow Row in dgv.Rows)
            {

                {
                    var conn2 = new SqlConnection(@"Data Source = MOHAMEDTHRWAT20\SQLEXPRESS; Initial Catalog = SharpControl; Integrated Security = True");
                    var cmd2 = new SqlCommand("", conn2);



                    cmd2.CommandText = "update UserPr set UseID=@UseID,UseName=@UseName,ScreenId=@ScreenId,ScreenName=@ScreenName, CanShow =@CanShow, CanOpen = @CanOpen ,  CanEdit = @CanEdit ,CanDelete = @CanDelete , CanPrint = @CanPrint  WHERE UseID='" + TXT_ID.Text + "'";

                    cmd2.Parameters.AddWithValue("@UseID", dgv.Rows[0].Cells[1].Value.ToString());
                    cmd2.Parameters.AddWithValue("@UseName", dgv.Rows[0].Cells[2].Value.ToString());
                    cmd2.Parameters.AddWithValue("@ScreenId", dgv.Rows[0].Cells[3].Value.ToString());
                    cmd2.Parameters.AddWithValue("@ScreenName", dgv.Rows[0].Cells[4].Value.ToString());
                    cmd2.Parameters.AddWithValue("@CanShow", dgv.Rows[0].Cells[5].Value.Equals(true || false));
                    cmd2.Parameters.AddWithValue("@CanOpen", dgv.Rows[0].Cells[6].Value.Equals(true || false));
                    cmd2.Parameters.AddWithValue("@CanAdd", dgv.Rows[0].Cells[7].Value.Equals(true || false));
                    cmd2.Parameters.AddWithValue("@CanEdit", dgv.Rows[0].Cells[8].Value.Equals(true || false));
                    cmd2.Parameters.AddWithValue("@CanDelete", dgv.Rows[0].Cells[9].Value.Equals(true || false));
                    cmd2.Parameters.AddWithValue("@CanPrint", dgv.Rows[0].Cells[10].Value.Equals(true || false));
                    conn2.Open();
                    cmd2.ExecuteNonQuery();
                    access();

                    conn2.Close();

                }
            }
            updateaut();

        }
        MessageBox.Show("update sucess");

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

 


Answers (4)