views:

103

answers:

5

How to construct new variable in C#.

I mean, to have sth like this

public void updateXXX(string endingOfVariable, int newValue)
{
   this.textBox_{endingOfVariable} = newValue;
}

This is implemented in Php:

$a = 'var'; $b = 'iable';
$variable = 'var';
echo ${$a.$b};

But maybe it is possible in C#.

The problem is that - I created ~500 textBoxes in C# Windows Form, and if I want to set a value, I need to build a switch() {case:; } statment with 500's cases.

+6  A: 

If you've assigned a name to each TextBox, you could create dictionary mapping the names to controls:

var boxes = form.Controls.OfType<TextBox>().ToDictionary(t => t.Name);

public void Update(string name, int newValue)
{
    boxes[name].Text = newValue.ToString();
}
dtb
@dtb: +1, That's a really slick way to build the dictionary.
Eric J.
You should add a .Where(t => !string.IsNullOrEmpty(t.Name)) before the ToDictionary to prevent catching TextBox's without names and causing an exception building the dictionary.
chuckj
A: 

Having 500 text boxes in an Windows Form can be a problem in and of itself (too many controls can be slow).

One way to do this is to put the controls in a dictionary when you create them (hopefully you are creating them programatically), then use the dictionary key to pull out the control you need.

Eric J.
I already created them in windows form as a visual programming(drag n drop, then format them as I need) - what I can do now?
ozzWANTED
You manually dragged and dropped _500_ textboxs and gave renamed them? Yikes, I hope you were paid.
Callum Rogers
Yep, In my job I was required - 'you must do it, and it's your prob if you don't want how', so 'I did' :D
ozzWANTED
A: 

You need to use reflection

  static void Main( string[] args )
  {
    Type type = typeof(MyClass);
    object o = Activator.CreateInstance(type);

    FieldInfo field = type.GetField("text", BindingFlags.NonPublic | BindingFlags.Instance);
    field.SetValue(o, "www.domain.com");
    string text = (string)field.GetValue(o);

    Console.WriteLine(text);

  }

from java2s

Paul Creasey
He doesn't **need** to use Reflection. FindControl would be much smarter, imo.
ANeves
@sr pt: Yea i agree, reflection is the general solution, but with forms controls then FindControl is probably better. Didn't think of it.
Paul Creasey
+4  A: 

Ignoring the fact you're doing a switch statement with 500 cases, you can use the FindControl method, and cast it to a TextBox.

((TextBox)FindControl("textbox_" + endingOfVariable)).Text = newValue;
Brandon
A: 

No way dude. You just can't do that.

Rosdi