C# 基于DataGridView的ComboBox值启用或禁用文本框
我有一个C# 基于DataGridView的ComboBox值启用或禁用文本框,c#,.net,C#,.net,我有一个DataGridView,其中一个ComboBox列和一个TextBox列动态创建,如下所示 DataGridViewComboBoxColumn dcColor = new DataGridViewComboBoxColumn(); dcColor.HeaderText = "Color"; dcColor.Items.Add("Red"); dcColor.Items.Add("Green"); DataGridViewTextBoxColumn dcValue = new Dat
DataGridView
,其中一个ComboBox
列和一个TextBox
列动态创建,如下所示
DataGridViewComboBoxColumn dcColor = new DataGridViewComboBoxColumn();
dcColor.HeaderText = "Color";
dcColor.Items.Add("Red");
dcColor.Items.Add("Green");
DataGridViewTextBoxColumn dcValue = new DataGridViewTextBoxColumn();
dcValue.HeaderText = "Value";
DataGridView1.Columns.Insert(0, dcColor);
DataGridView1.Columns.Insert(1, dcValue);
现在,如果用户在组合框中选择“红色”项,则相应的文本框单元格应被禁用,并以灰色显示。如果用户选择“绿色”项,则应启用相应的文本框单元格
另外,在关闭datagridview窗体之前,如果选择绿色,我们如何确保用户输入数据。使用datagridview的CellValueChanged事件,检查是否有任何单元格值更改。无论是TextBoxColumn还是ComboBoxColumn,这对所有列类型都适用 检查是否有正确的列,在您的示例中,颜色列插入到位置0。 在您的示例中,当选择“红色”时,将索引1上的其他列设置为只读
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
if (e.ColumnIndex == 0) {
bool disable = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "Red";
dataGridView1.Rows[e.RowIndex].Cells[1].ReadOnly = disable;
}
}
第二个问题的答案是使用表单的FormClosing事件并验证其中的行。如果数据不正确,您可以通过设置
e.cancel=true来取消关闭请求。以下代码适用于组合框中的项目选择
private void _DataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if ((sender as DataGridView).SelectedCells[0].GetType() == typeof(DataGridViewComboBoxCell))
{
if ((e.Control as ComboBox) != null)
{
(e.Control as ComboBox).SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
(e.Control as ComboBox).SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
}
}
}
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if ((sender as ComboBox).SelectedItem.ToString() == "Red")
{
_DataGridView.Rows[_DataGridView.CurrentCell.RowIndex].Cells[1].ReadOnly = true;
}
else
{
_DataGridView.Rows[_DataGridView.CurrentCell.RowIndex].Cells[1].ReadOnly = false;
}
}
如何使用EditingControlShowing事件来捕获TextBox和ComboBox的值/属性,并实现前面提到的功能。