简体   繁体   中英

Compare TextBox Controls by Name property

I have a KeyPress event bound on multiple TextBox s and I want to check which TextBox is getting clicked and do different things depending on the one clicked.

I'm trying to compare which TextBox is getting clicked based on the .Name attribute of the text box. I'm doing this in a switch statement, but am getting a Constant value is expected .

private void UpdateValues(object sender, KeyPressEventArgs e)
{
    TextBox textBox = (TextBox)sender;

    switch (textBox.Name)
    {
        case txtBox1.Name: // Error here
            break;
    }
}

Is there a way to get around this? I don't want to hard code the .Name as a string in case future developers work on this.

Can I do this, or will it become a run time error?

private const string _TXTBOX1NAME = txtBox1.Name;


private void UpdateValues(object sender, KeyPressEventArgs e)
{
    TextBox textBox = (TextBox)sender;

    switch (textBox.Name)
    {
        case _TXTBOX1NAME: // Use the const variable
            break;
    }
}

EDIT:

Actually, you cannot assign const values like that.

How would I compare which TextBox has a KeyPress without hard coding the .Name as a string in the case statement?

You can't use the switch like that. The case s need to be compile-time constants.

You could do:

private void UpdateValues(object sender, KeyPressEventArgs e)
{
    TextBox textBox = (TextBox)sender;

    switch (textBox.Name)
    {
        case "NameTextBox": 
            break;
        case "PasswordTextBox":
            break;
    }
}

If you know the names, this would be possible. Your example fails, because textbox1.Name is not a constant, but a property read from the instance of one TextBox .

Another way would be to use the textbox reference, given as the sender:

private void UpdateValues(object sender, KeyPressEventArgs e)
{
    TextBox textBox = (TextBox)sender;

    if(textBox == textBox1) { ... }
    if(textBox == textBox2) { ... }
}

But IMHO the best solution would be to use two change-callbacks, one for each method. Then you do not need to compare the textbox es or the textbox 's names.

So you could change UpdateValues into one UpdateUserName and UpdatedPasswort . Doing this, the method name will clearly show, what the method does(, or at least should do), making your code a lot more readable.

try this

private void UpdateValues(object sender, KeyPressEventArgs e)
{
    TextBox textBox = (TextBox)sender;

    if (textBox.Name == textBox1.Name){
          //error
    } else if(textBox.Name == textBox2.Name){
          // and so on
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM