user589195
user589195

Reputation: 4250

Identify which textbox has fired a text changed event

I have a number of text boxes that are dynamically created via code.

I would like to be able to assign a generic event handler to all the textboxes for the text changed even and then within the handler determine which text box has fired the event.

Code I have is:

txtStringProperty.TextChanged += TextBoxValueChanged;

private void TextBoxValueChanged(object sender, RoutedEventArgs e)
{
    string propertyName = // I would like the name attribute of the textbox here
}

Please let me know if you require anymore information.

Upvotes: 4

Views: 11135

Answers (3)

Danny Mor
Danny Mor

Reputation: 1273

My advice is to look at the base class hierarchy at MSDN and just cast the control to it and extract the properties defined on it:

var name = ((ContentControl) sender).Name;

this is also a good practice for a more generic implementation because casting it to 'TextBox' means you can apply the handling logic to that type of control only.

Upvotes: 0

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48600

Cast object sender(your textbox which fired event) to TextBox.

If only one property is what you want then write

string propertyName = ((TextBox)sender).Name; 

But when more than one property is required, then it is better to create a Textbox variable and use it like.

TextBox txtbox =  (TextBox)sender;

Then you can use any property of it like

string propertyName = txtbox.Name; 

MessageBox.Show(proptertyName);
MessageBox.Show(txtbox.Content.ToString());

Upvotes: 2

Sjoerd
Sjoerd

Reputation: 75679

The sender parameter contains which control has fired the event. You can cast it to a TextBox and get the name property from it:

string propertyName = ((TextBox)sender).Name;

Upvotes: 7

Related Questions