-1

有时,当用户在 DataGridViewTextBox 中键入文本时,您想要启用或禁用控件,具体取决于键入的值。例如,在您输入正确的值后启用按钮

Microsoft 在一篇关于如何创建可以禁用的 DataGridViewButtonCell 的文章中展示了这种方法。

这是他们的把戏(也可以在其他解决方案中看到)

  • 确保您收到事件 DataGridView.CurrentCellDirtyStateChanged
  • 收到此事件后,通过调用提交当前单元格中的更改: DataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
  • 此提交将导致事件 DataGridView.CellValueChanged
  • 确保在引发此事件时收到通知
  • 在您的 OnCellValueChanged 函数中,检查更改值的有效性并决定是否启用或禁用相应的控件(例如按钮)。

这工作正常,除了 CommitEdit 使文本在 OnCellValueChanged 中被选中。因此,如果您想输入 64,您会在输入 6 时收到通知,然后在输入 4 时收到通知。但是因为选择了 6,所以您没有得到 64,而是将 6 替换为 4。不知何故,代码必须取消选择 6在解释值之前在 OnCellValueChanged 中。

属性 DataGridView.Selected 不起作用,它不会取消选择文本,但会取消选择单元格。

那么:如何取消选择所选单元格中的文本?

4

1 回答 1

1

我认为您需要一些东西,当用户在当前单元格中键入一些文本时,您需要知道当前文本(甚至在提交之前)以检查是否需要禁用某些按钮。因此,以下方法应该适合您。你不需要提交任何东西,只处理TextChanged当前编辑控件的事件,编辑控件只在EditingControlShowing事件处理程序中暴露,代码如下:

//The EditingControlShowing event handler for your dataGridView1
private void dataGridView1_EditingControlShowing(object sender, 
                                          DataGridViewEditingControlShowingEventArgs e){
   var control = e.Control as TextBox;
   if(control != null && 
      dataGridView1.CurrentCell.OwningColumn.Name == "Interested Column Name"){
      control.TextChanged -= textChanged_Handler;
      control.TextChanged += textChanged_Handler;
   }
}
private void textChanged_Handler(object sender, EventArsg e){
  var control = sender as Control;
  if(control.Text == "interested value") {
     //disable your button here
     someButton.Enabled = false;
     //do other stuff...
  } else {
     someButton.Enabled = true;
     //do other stuff...
  }
}

请注意,我上面使用的条件可以根据您的需要进行修改,这取决于您。

于 2013-12-17T11:44:35.697 回答