Update mysql database from datagridview selected row

前端 未结 1 739
忘掉有多难
忘掉有多难 2021-01-27 07:38

i have a datagridview which loads mysql database table t_pi_clients on form load event,and i have another tab which contains textboxes of the respective columns of t_pi_client,

相关标签:
1条回答
  • 2021-01-27 07:59

    This is just a pseudocode of what you need to do

    string cmdText = @"UPDATE t_pi_Clients
                     SET ClientName = @ClientName,
                         PostalAdd = @PostalAdd,
                         Telephone = @Telephone,
                         Fax = @Fax,
                         .... etc ....
                     WHERE ClientCode = @ClientCode";
    using(MySqlConnection cn = new MySqlConnection(.....))
    using(MySqlCommand cmd = new MySqlCommand(cmdText, cn))
    {
        cn.Open();
        cmd.Parameters.AddWithValue("@ClientName", txtboxClientName.Text);
        cmd.Parameters.AddWithValue("@PostalAdd", txtboxPostalAddress.Text);
        ....etc etc...
        cmd.Parameters.AddWithValue("@ClientCode", textboxClientCode.Text);
        int rowsUpdated = cmd.ExecuteNonQuery();
        if(rowsUpdated > 0) 
        {
            // extract the code that loads DataGridView1 from the Form_Load
            // and create a reusable method that you could call from here
        }
    }
    

    First you build an sql command text with the UPDATE clause. I assume that your primary key (the field that uniquely identifies your records) is the ClientCode field.

    Then create the connection and the command. Fill the command parameters collection with the parameters required by your text taking the values from the TextBoxes.
    Call the ExecuteNonQuery to store the values.

    If you succeed then you need to update or reload your datagridview. The best approach would be setting one by one the gridview cells of the current row with the new values from the textboxes, or you could simply extract the code used in form_load to fill the grid and make a new method that you could call from the button click event. (But this could be slower if you have many records)

    0 讨论(0)
提交回复
热议问题