2009-05-18 96 views
2

我有一個datagridview的形式,當用戶開始輸入第一行的單元格的值時,也可以按提交該值的f2,但我不能訪問單元格的值,除非用戶打標籤並轉到另一個小區訪問Datagridview單元格值,而其值正在編輯

以下是我的訪問單元格值時F2被命中代碼

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
    { 
     var key = new KeyEventArgs(keyData); 

     ShortcutKey(this, key); 

     return base.ProcessCmdKey(ref msg, keyData); 
    } 


    protected virtual void ShortcutKey(object sender, KeyEventArgs key) 
    { 
     switch (key.KeyCode) 
     { 
      case Keys.F2: 
       MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString()); 
       break; 
     } 
    } 

dataGridView1.SelectedCells [0]。價值返回null

回答

2

@BFree感謝你的代碼啓發了我;)爲什麼不只是調用this.dataGridView1.EndEdit();在MessageBox.Show(dataGridView1.SelectedCells [0] .Value.ToString())之前的 ;

此代碼的工作就好了:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
    { 
     var key = new KeyEventArgs(keyData); 

     ShortcutKey(this, key); 

     return base.ProcessCmdKey(ref msg, keyData); 
    } 


    protected virtual void ShortcutKey(object sender, KeyEventArgs key) 
    { 
     switch (key.KeyCode) 
     { 
      case Keys.F2: 
dataGridView1.EndEdit(); 
       MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString()); 
       break; 
     } 
    } 
+0

這完全爲我工作,謝謝! – anon58192932 2012-10-05 23:29:06

5

如何做這樣的事情,而不是。掛鉤DataGridView的「EditingControlShowing」事件並在那裏捕獲F2。有些代碼:

public partial class Form1 : Form 
{ 
    private DataTable table; 
    public Form1() 
    { 
     InitializeComponent(); 
     this.dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(HandleEditingControlShowing); 
     this.table = new DataTable(); 
     table.Columns.Add("Column"); 
     table.Rows.Add("Row 1"); 
     this.dataGridView1.DataSource = table; 
    } 


    private void HandleEditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
    { 
     var ctl = e.Control as DataGridViewTextBoxEditingControl; 
     if (ctl == null) 
     { 
      return; 
     } 

     ctl.KeyDown -= ctl_KeyDown; 
     ctl.KeyDown += new KeyEventHandler(ctl_KeyDown); 

    } 

    private void ctl_KeyDown(object sender, KeyEventArgs e) 
    { 
     var box = sender as TextBox; 
     if (box == null) 
     { 
      return; 
     } 

     if (e.KeyCode == Keys.F2) 
     { 
      this.dataGridView1.EndEdit(); 
      MessageBox.Show(box.Text); 
     } 
    } 

}

的想法很簡單,你鉤到EditingControlShowing事件。每當單元格進入編輯模式時,就會被觸發。最酷的是,它暴露了實際的底層控制,並且可以將它投射到實際的Winforms控件上,並像平常一樣將其掛接到所有事件上。

1

你可以試試這個

string str = dataGridView.CurrentCell.GetEditedFormattedValue 
      (dataGridView.CurrentCell.RowIndex, DataGridViewDataErrorContexts.Display) 
      .ToString();