2016-04-11 3 views
-1

私は10のテキストボックスを持っています。私はそれを呼び出すときに私はパラメータを送信できるように共通のKeyDown関数が必要です。私はtextbox1にテキストを入力し、 "Enter"キーを押してから、KeyDown関数呼び出し時にパラメータとして送るテキストボックス(たとえば:textbox2)をフォーカスします。KeyDown関数C#のパラメータとしてテキストボックスを送信するには?

private void textBox1_KeyDown(object sender, KeyEventArgs e) 
    { 
     if(e.KeyCode == Keys.Enter) 
     { 
      textBox2.Focus(); 
     } 
    } 
+1

[ヘルプ]と​​特に[ask] – Steve

+2

Uhをお読みください。 C#のほとんどすべてのリスナーは既にオブジェクト送信者を含んでいます... – Nyerguds

+0

@Nyerguds私は彼が 'textBox1'のリックイベントで、自分自身以外のtextBox、たとえば' textBox2'を渡したいと言っていると思いますパラメータとして –

答えて

1

ドミトリー・バイチェンコの答えは必要な基礎を持っています。しかし、あなたは常にテキストボックスを選択したい場合は、まずそのためのリストのいくつかの種類を必要とし、あなたのクラスのコンストラクタでそれを埋めるよ:

private TextBox[] textBoxOrder; 

public Form Form1() 
{ 
    InitializeComponent(); 
    textBoxOrder = new TextBox[] 
    { 
     textBox1, textBox2, textBox3, textBox4, textBox5, 
     textBox6, textBox7, textBox8, textBox9, textBox10 
    }; 
} 

は、その後、あなたのキーリスナーに、あなたが行うことができます次のものを選択してください:

TextBox nextBox = null; 
for (Int32 i = 0; i < textBoxOrder.Length; i++) 
{ 
    if (textBoxOrder[i] == sender) 
    { 
     if (i + 1 == textBoxOrder.Length) 
      nextBox = textBoxOrder[0]; // wrap around to first element 
     else 
      nextBox = textBoxOrder[i + 1]; 
     break; 
    } 
} 
if (nextBox != null) 
    nextBox.Focus(); 
2

TextBoxインスタンスがsenderパラメータを経由して送信されます。

private void textBox1_KeyDown(object sender, KeyEventArgs e) 
{ 
    TextBox textBox = sender as TextBox; 

    if (e.KeyCode == Keys.Enter) 
    { 
     // if we can focus: 
     // 1. it's a textbox instance that has called Key Down event 
     // 2. the textbox can be focused (it's visible, enabled etc.) 
     // then set keyboard focus 
     if ((textBox != null) && textBox.CanFocus) 
     { 
      textBox.Focus(); 
      // you may find useful not proceeding "enter" further 
      e.Handled = true; 
     } 
    } 
} 

はあなたが興味のすべてテキストボックス(textBox1 ... textBox10ため同じtextBox1_KeyDown方法を割り当てたことを、確認してください)

関連する問題