c# - 根据复选框值更新 datagridview - 循环所有行的复选框并检查是否已选中任何复选框
问题描述
所以我有这个 DataGridView,上面有三列,在这个日期和用户名是从我的 SQL Server 数据库中检索的。现在,在第一列中,我们有一个位字段,在我的 Windows 应用程序设计器中显示为 CheckBox。
所以,我想,在单击更新按钮时,我的程序想要检查是否已选中任何复选框,如果复选框已被选中,那么更新逻辑应该触发。
如果没有选中复选框,则应抛出错误。
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
推荐阅读
- python-3.x - 无法访问数据框的列
- java - 在重载构造函数后总是执行一些代码
- c++ - 在增强精神中用不同的字符串替换点燃
- php - 将带有排序、搜索和分页功能的引导表添加到我的 PHP 函数中
- linux - 如何创建具有两个电子邮件服务器作为后端电子邮件服务器的电子邮件网关
- xslt - XSL-FO 在 break-before 创建空页面时删除静态内容
- c++ - 强制 format_to_n 使用终止零
- php - Jquery根据天数和使用jquery的开始日期获取结束日期
- python - Neat-Python 实现 - “模块”对象不可调用
- php - Laravel dompdf 自定义字体目录