【问题标题】:Enable or Disable Textbox based on ComboBox value of DataGridView根据 DataGridView 的 ComboBox 值启用或禁用文本框
【发布时间】:2013-07-16 14:21:47
【问题描述】:

我有一个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);

现在,如果用户在 ComboBox 中选择“红色”项,则应禁用相应的 TextBox 单元格并以灰色显示。
如果用户选择“绿色”项,则应启用相应的 TextBox 单元格。

另外,在关闭datagridview表单之前,我们如何确保用户在选择绿色时输入数据。

【问题讨论】:

  • 我如何使用 EditingControlShowing 事件,它可以捕获 TextBox 和 ComboBox 的值/属性并实现上述内容。

标签: c# .net


【解决方案1】:

使用 DataGridView 的 CellValueChanged-Event,检查是否有任何单元格值发生了变化。这对所有列类型(无论是 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-Event 并验证其中的行。如果数据不正确,您可以通过设置e.Cancel = true 取消关闭请求。

【讨论】:

    【解决方案2】:

    以下代码适用于 ComboBox 中的项目选择

    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;  
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 1970-01-01
      相关资源
      最近更新 更多