Search code examples
wpfc#-4.0textboxonkeydown

Get Sender TextBox Name in Event Keydown


I am working on an application using WPF and C#. On a window I have number of textBoxes arranged in a grid of 5 columns and rows as many as user needs. It works like this: Initially the 1st row of 5 textBoxes is visible, the user enters appropriate values and as soon as he hits ENTER in the 5th textBox of the row, a new similar row of textBoxes is generated for newer entries. This keep on happening. Each textBox has a unique name using RegisterName method and loop.

Now my problem is that suppose I have already created 5 rows with around 25 textBoxes on window. I focus on one of the textBoxes of the 3rd row and type something that fires it appropriate KeyDown Event. In this keydown event, I need the Name of all the textBox that caused this event. How can I do that?

This, being done, will also help me to access all the other textBoxes of that row as I know the nomenclature using which they are named. Please help.


Solution

  • You can try something like:

    Note we also set the Name property along with the FrameworkContentElement.RegisterName function.

    var box = new TextBox();
    var itemName = "Unique Identifier";  // Change this to your unique name per box
    this.RegisterName(itemName, box);
    box.Name = itemName;
    box.KeyDown += (sender, args) => {
      var textBox = sender as TextBox;
      if (textBox != null)
        MessageBox.Show(textBox.Name);  // Would show "Unique Identifier"
    };