[英]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. 我有带复选框列的datagridview,我想在单击按钮时更新一个值。待处理状态= 0和已批准状态= 1。 If I code
如果我编码
UPDATE pending SET status='1' WHERE status='0'
All status='0' will be '1' even the row without check. 即使没有检查的行,所有状态=“ 0”也将为“ 1”。 I want to update status to 1 only to the selected rows.
我只想将所选状态的状态更新为1。 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. 假设您的数据库主键名为ID,并且它位于网格的位置0,那么您应该能够在命令中使用ID来仅修改该记录。
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! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.