2009-05-18 49 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();