2011-09-30 29 views
0

我有一個綁定的datagridview.when我選擇datagridview中的單元格,然後按Enter,我想要一個事件被提出,將選定的單元格的行的第一列值傳遞給另一個窗體。怎麼做?輸入密鑰的Datagridview事件

+1

你試過了什麼?這是winforms嗎?你如何綁定數據?你能顯示一些代碼嗎? –

+1

您可以訂閱單元格的關鍵事件,然後在找到Enter鍵時執行操作。 – V4Vendetta

回答

0

假設這是WinForms,您可以訂閱其中一個Key事件並使用該事件。

例如,這裏使用的是KeyUp事件。

DataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler (DataGridView1_EditingControlShowing); 

private void dbg_EditingControlShowing (object sender, DataGridViewEditingControlShowingEventArgs e) { 
     TextBox txb = e.Control as TextBox; 
     txb.PreviewKeyDown += (S, E) => { 
      if (E.KeyCode == Keys.Enter) { 
       DataGridView1.CurrentCell = dbg.CurrentRow.Cells["Column_name"]; 
       //Or any code you ... 
      } 
     }; 
} 
+0

它給錯誤 - System.NullReferenceException未處理 Message =「對象引用未設置爲對象的實例。」 – pavan

+0

你在哪一行發生錯誤? –

1

我用_EditingControlShowing事件到DataGridView並使用PreviewKeyDown在此單元格中的代碼解決了這個問題:

public partial class Form2 : Form 
{ 
    public string Id = string.Empty; 
    public Form2(string FormOneID) 
    { 
     InitializeComponent(); 
     Id = FormOneID; 
    } 

    private void Form2_Load(object sender, EventArgs e) 
    { 
     MessageBox.Show("FormOne ID" + Environment.NewLine + Id + Environment.NewLine + "Displaying on FormTwo"); 
    } 
} 
0

表1個代碼:

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     DataTable dt = new DataTable(); 
     dt.Columns.Add("ID"); 
     dt.Columns.Add("Name"); 
     dt.Rows.Add(); 
     dt.Rows[dt.Rows.Count - 1][0] = "1"; 
     dt.Rows[dt.Rows.Count - 1][1] = "Stackoverflow"; 
     dataGridView1.DataSource = dt; 
    } 
    string ID = string.Empty; 
    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
    { 
     ID = dataGridView1.SelectedRows[0].Cells["ID"].Value.ToString(); 
    } 
     private void dataGridView1_KeyUp(object sender, KeyEventArgs e) 
    { 
     if (e.KeyCode == Keys.Enter) 
     { 
      Form2 frmTwo = new Form2(ID); 
      frmTwo.Show(); 
     } 
    } 
} 

表2編號

private void myDataGridView_KeyUp(object sender, KeyEventArgs e) 
{ 
     // nothing is selected 
     if (myDataGridView.SelectedRows.Count == 0) 
      return; 

     if (e.KeyCode == Keys.Enter) 
     { 
      string firstColumnValue = myDataGridView.SelectedRows[0].Cells[0].Value.ToString(); 

      // passes the value through the constructor to the 
      // second form. 
      MySecondForm f2 = new MySecondForm(firstColumnValue); 
      f2.Show(); 
     } 
} 
1
void TextBox1_KeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.KeyCode == Keys.Enter) 
    { 
     e.Handled = true; 
    } 
} 

void TextBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) 
{ 
    if (e.KeyCode == Keys.Return) 
    { 
     /* Your code here! */ 
    } 
}