Muhammad Ehsan
Muhammad Ehsan

Reputation: 11

C# Detect textBox in KeyPress Event From Multiple textBoxes

I have 5 textBoxes which access the same KeyPressEvent() How do I detect from which textBox Currently key is Pressed ?

 private void textBox_Department_KeyPress(object sender, KeyPressEventArgs e)
    {

       e.Handled = !(Char.IsLetter(e.KeyChar) | e.KeyChar == (char)Keys.Back | e.KeyChar==(char)Keys.Space);
    }

Upvotes: 0

Views: 579

Answers (2)

wingerse
wingerse

Reputation: 3796

You could use the Tag property or even use x:Name and check if sender is equal to it.

For example, if you were to use tag, you could do this to your TextBoxes.

<TextBox Tag="textBox1"../>

then in your code, you can cast sender to TextBox and check if it's tag is equal to whatever you want.

var textBox = (TextBox)sender;
if(textBox.Tag == "textBox1"){}

Or even better, check the sender itself:

var textBox = (TextBox)sender;
if(textBox == myTextBoxNameInXName){}

Upvotes: 1

Jiri P.
Jiri P.

Reputation: 420

In the event signature, the object sender is the object (in your case TextBox) that invokes the KeyPress event.

Upvotes: 1

Related Questions