0

In the below example is it possible to use the kvp.value to point a global variable (num1, num2, num3)?

int num1;
int num2;
int num3;


private void button1_Click(object sender, EventArgs e)
{
   List<KeyValuePair<TextBox, string>> myList = new List<KeyValuePair<TextBox, string>>(); 
   myList.Add(new KeyValuePair<TextBox, string>(textBox1, "num1"));
   myList.Add(new KeyValuePair<TextBox, string>(textBox2, "num2"));
   myList.Add(new KeyValuePair<TextBox, string>(textBox3, "num3"));

          foreach (KeyValuePair<TextBox, string> kvp in myList)
          {
              TextBox tb= kvp.Key;
              try
              {
                  num1 = int.Parse(tb.Text);
                  //instead of using the hardcoded variable name num1 i want to use kvp.value
                  //kvp.value = int.Parse(tb.Text);
              }
              catch
              {
                  //blah blah
              }

          }

}

I deleted my previous post as it was very unclear, hopefully this is a bit better.

6
  • dotnetperls.com/reflection-field i think it's what you want Commented Dec 7, 2014 at 14:09
  • Do you need to use the variable num1, num2, num3 anywhere else in the code? Commented Dec 7, 2014 at 14:10
  • yes they are used else where Commented Dec 7, 2014 at 14:11
  • 2
    I would suggest a dictionary<string, int> would be more performant and provide what you want here. Commented Dec 7, 2014 at 14:14
  • 1
    You should consider using 'enum' to have a set of named integers. Best regards, Commented Dec 7, 2014 at 14:14

1 Answer 1

1

It's easier if you can change your global variables (from int) to reference type, by introducing a wrapper class:

class Number<T>
{
    public Number(T value)
    {
        Value = value;
    }

    public T Value { get; set; }
}

Your code will be:

Number<int> num1 = new Number<int>(0);
Number<int> num2 = new Number<int>(0);
Number<int> num3 = new Number<int>(0);



private void button1_Click(object sender, EventArgs e)
{
    List<KeyValuePair<TextBox, Number<int>>> myList = new List<KeyValuePair<TextBox, Number<int>>>();
    myList.Add(new KeyValuePair<TextBox, Number<int>>(textBox1, num1));
    myList.Add(new KeyValuePair<TextBox, Number<int>>(textBox2, num2));
    myList.Add(new KeyValuePair<TextBox, Number<int>>(textBox3, num3));

    foreach (KeyValuePair<TextBox, Number<int>> kvp in myList)
    {
        TextBox tb = kvp.Key;
        try
        {
            kvp.Value.Value = int.Parse(tb.Text);
            //instead of using the hardcoded variable name num1 i want to use kvp.value
            //kvp.value = int.Parse(tb.Text);
        }
        catch
        {
            //blah blah
        }

    }

}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.