2013-12-16 22 views
-1

有時,用戶在DataGridViewTextBox中輸入文本時,要啓用或禁用控件,具體取決於要輸入的值。例如,在鍵入正確值後啓用按鈕取消選擇DataGridViewTextBoxCell中的文本.CommitEdit(DataGridViewDataErrorContexts.Commit)

Microsoft在文章中介紹瞭如何創建可禁用的DataGridViewButtonCell。

這是他們的把戲(它也可以在其他方案可以看出)

  • 確保你的事件DataGridView.CurrentCellDirtyStateChanged
  • 在收到此事件,通過提交當前單元格的變化調用: DataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
  • 此承諾將導致事件DataGridView.CellValueChanged
  • 確保當引發此事件
  • 在你OnCellValueChanged功能你收到此通知,確認改變值的有效性,並決定是否 啓用或禁用相應的控制(例如按鈕)。

這很好,除了CommitEdit使得在OnCellValueChanged中選擇文本。所以如果你想輸入64,你會在輸入6時得到通知,當你輸入4時會得到通知。但是因爲選擇了6,所以你不會得到64,但是6被替換爲4. 不知何故代碼必須取消選擇在解釋值之前在OnCellValueChanged中添加6。

DataGridView.Selected屬性沒有這樣做,它不取消選擇文本,但取消選擇單元格。

所以:如何取消選中單元格中的文本?

回答

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

請注意,我用的條件以上可以根據你的需要進行修改,這取決於你。