简体   繁体   中英

Updating data of selected row in datagridview

I have datagridview with checkbox column and I want to update one value on a button click.Pending status=0 and Approved status=1. If I code

UPDATE pending SET status='1' WHERE status='0'

All status='0' will be '1' even the row without check. I want to update status to 1 only to the selected rows. My codes are as follows:

private void btnApproved_Click(object sender, EventArgs e)
    {


        List<DataGridViewRow> selectedRows = (from row in gvPending.Rows.Cast<DataGridViewRow>() where Convert.ToBoolean(row.Cells["checkBoxColumn"].Value) == true select row).ToList();
        if (MessageBox.Show(string.Format("Do you want to approve these rows?"), "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
        {
            foreach (DataGridViewRow row in selectedRows)
            {
                using (var connect = sqlcon.getConnection())
                {
                    using (SqlCommand cmd = new SqlCommand("UPDATE pending SET status='1' WHERE /* checkboxColumnValue is true */  "))
                    {
                        cmd.Connection = connect;
                        connect.Open();
                        //cmd.ExecuteNonQuery();
                        //connect.Close();

                    }
                }
            }
            this.BindGrid();
            //this.BindGrid1();
            //this.BindGrid2();
        }
    }

Any suggestions or corrections? Thanks!

Assuming that your database primary key is named ID and that it is at position 0 of your grid then you should be able to use the ID in your command to modify only that record.

using (var connect = sqlcon.getConnection())
{
    string updateRecordCmd = String.Format( "UPDATE pending SET status='1' WHERE ID={0}",row.Cells[0].Value.toString());  
    using (SqlCommand cmd = new SqlCommand(updateRecordCmd))
    {
        cmd.Connection = connect;
        connect.Open();
        //cmd.ExecuteNonQuery();
        //connect.Close();

    }
}

Good Luck!

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