DataGridView选中行后根据SQL数据设置CheckBox勾选状态问题
问题:DataGridView选中行后无法设置CheckBox勾选状态
我在WinForms项目中实现DataGridView选中行后,将SQL数据同步到界面控件。目前TextBox和ComboBox的赋值正常,但CheckBox的勾选状态无法按规则设置(SQL中"Yes"对应勾选True,"No"对应未勾选False)。
现有代码片段
控件赋值代码
textBox4.Text = row.Cells[11].Value.ToString(); //other/notes textBox3.Text = row.Cells[3].Value.ToString(); //Monitor textBox1.Text = row.Cells[0].Value.ToString(); //Firstname textBox2.Text = row.Cells[1].Value.ToString(); //Surname comboBox1.Text = row.Cells[2].Value.ToString(); //Company comboBox3.Text = row.Cells[4].Value.ToString(); //Laptop/Nuc checkBox1. = row.Cells[5].Value.ToString(); //keyboard
DataGridView绑定代码
BindingSource bs = new BindingSource(); bs.DataSource = dataGridView1.DataSource; bs.Filter = "Firstname Like '" + textBox1.Text + "%' and lastname Like '" + textBox2.Text + "%' and Company '" + comboBox1.Text + "%'"; dataGridView1.DataSource = bs.DataSource;
解决方案
1. 修正CheckBox赋值的语法与逻辑错误
你的代码存在语法错误(checkBox1. = ...缺少属性名),同时需要根据单元格值判断勾选状态:
// 处理空值避免空引用异常 string keyboardStatus = row.Cells[5].Value?.ToString() ?? string.Empty; // 忽略大小写判断,兼容"Yes"/"yes"/"YES"等情况 checkBox1.Checked = keyboardStatus.Equals("Yes", StringComparison.OrdinalIgnoreCase);
2. 修复BindingSource Filter的语法错误
Filter语句中Company字段缺少Like关键字,同时建议处理单引号避免语法错误:
// 转义单引号,防止用户输入导致Filter语法错误 string firstName = textBox1.Text.Replace("'", "''"); string lastName = textBox2.Text.Replace("'", "''"); string company = comboBox1.Text.Replace("'", "''"); BindingSource bs = new BindingSource(); bs.DataSource = dataGridView1.DataSource; bs.Filter = $"Firstname Like '{firstName}%' and lastname Like '{lastName}%' and Company Like '{company}%'"; dataGridView1.DataSource = bs; // 直接赋值BindingSource即可,无需取bs.DataSource
3. 可选:直接绑定控件到BindingSource(推荐)
如果想省去手动赋值的步骤,可以在窗体初始化时将CheckBox直接绑定到BindingSource的对应列,选中行时自动同步状态:
// 假设你的数据源中对应列名为"keyboard",替换为实际列名 checkBox1.DataBindings.Add( "Checked", bs, "keyboard", true, DataSourceUpdateMode.OnPropertyChanged, false // 当值为空时的默认状态 );
这种方式无需在选中行事件中编写赋值代码,控件会自动与数据源同步。
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

