基于复选框值更新数据网格视图 - 循环所有行的复选框并检查是否已选中任何复选框



所以我有这个DataGridView,上面有三列,在这个日期和用户名是从我的SQL Server数据库中重新恢复的。现在,在第一列中,我们有一个位字段,它在我的 Windows 应用程序设计器中显示为复选框。

所以,我想,在单击更新按钮时,我的程序想要检查是否已选中任何复选框,如果复选框已被选中,则应触发更新逻辑。

如果没有选中复选框,则应抛出错误。

public void Update_button_Click(object sender, System.EventArgs e) {

//Check all the checkbox in the first column and if none is selected throw error
If(boolean(checkbox.Row[0]) == true)  { //This is an example if-else condition code which i expect 
string msg = String.Format("Row: {0}, Column: {1}",
dataGridView1.CurrentCell.Value,
dataGridView1.CurrentCell.ColumnIndex);
MessageBox.Show(msg, "Current Cell");
dataadapter.Update((DataTable) bindingSource1.DataSource);
foreach(DataGridViewRow row in dataGridView1.Rows) {
if (Convert.ToBoolean(row.Cells[0].Value)) {
var myvalue = dataGridView1.Rows[row.Cells[0].RowIndex].Cells[dataGridView1.Columns["dummy_id"].Index].Value.ToString();
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MYConnectionString"].ConnectionString;
using(var connection = new SqlConnection(connectionString)) {
connection.Open();
using(var command = new SqlCommand(@ "[dbo].[SP]", connection)) {
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@id", SqlDbType.Int).Value = myvalue;
command.ExecuteNonQuery();
}
}
}
}
MessageBox.Show("SAVED");
selected_user_data();
}
// If no checkbox has been selected throw error.
Else { 
Messagebox.show("Please select checkbox")
}

我之前遇到过这个问题,我的解决方案是添加我所有的 GUI 元素(在你的例子中复选框,我的案例文本框(使它们易于迭代。然后,您可以检查其状态:

List<CheckBox> checkbox_list = new List<CheckBox>();
//proceed to manually add all checkboxes to this list upon program initialization
checkbox_list.Add(checkbox1);
//...
//so on until you are done
bool check = false; //we are looking for at least one true, so start with false
for(int i = 0; i < checkbox_list.Count; i++)
{
if(checkbox_list[i].Checked == true)
check = true;
}
if(check == true)
Console.WriteLine("At least one checkbox is checked.");
else
Console.WriteLine("No checkboxes checked.");
//use "check" bool to determine whether to update

相关内容

最新更新