Dante1986
Dante1986

Reputation: 59979

Is it possible to use a variable number in the name of a variable name?

(using WPF) Is it possible to use the number of a TextBox to select the parameter name? For example, the user can put 0,1,2 or 3 as text in the TextBox:

private void button1_Click(object sender, RoutedEventArgs e)
{
    int test = int.Parse(textBox1.Text);

    string nr1 = "this string is 1";
    string nr2 = "this string is 2";
    string nr3 = "this string is 3";

    MessageBox.Show();
}

Now for MessageBox.Show(); in want to put something as nr(test)
Would something like this be possible?

Upvotes: 2

Views: 132

Answers (5)

WiiMaxx
WiiMaxx

Reputation: 5420

You could also use FindName()

lets suggest this:

XAML

<StackPanel>
    <TextBox Height="23" Name="textBox1" Width="120" />
    <TextBox Height="23" Name="textBox2" Width="120" />
    <TextBox Height="23"  Name="textBox3" Width="120" />
    <Button Content="Button" Height="23"  Width="75" Click="button1_Click" />
</StackPanel>

your could would look like this

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        int number =2;
        TextBox tb = this.FindName(string.Format("textBox{0}", number)) as TextBox;

        MessageBox.Show(tb.Text);
    }

Upvotes: 1

SysDragon
SysDragon

Reputation: 9888

You can create a Dictionary<int,string> with all the data you want handled by keys:

MessageBox.Show(myDict[test])

Here you can see the MSDN Documentation.

Upvotes: 1

Fares
Fares

Reputation: 542

I recommend you to use a dictionary. Dealing with dictionaries simplifies your life. I suggest looking here.

Upvotes: 0

Richard Friend
Richard Friend

Reputation: 16018

Why not use a Dictionary ?

var dict = new Dictionary<int,string>();
dict.Add(1,"String Number 1");
dict.Add(2,"String Number 2");
dict.Add(3,"String Number 3");

int test = int.Parse(textBox1.Text);
MessageBox.Show(dict[test]);

Upvotes: 6

ojlovecd
ojlovecd

Reputation: 4902

I think this will help you:

private void button1_Click(object sender, RoutedEventArgs e)
        {
            int test = int.Parse(textBox1.Text);

            string[] nr = new string[3]{"this string is 1","this string is 2","this string is 3"};
            MessageBox.Show(nr[test-1]);
        }

Upvotes: 1

Related Questions