Using a variable in the selection of an object (textbox in this case)

230 Views Asked by At

I have a multiple textboxes in a form, and with the typed information I create an object called UserClass. I want to create multiple users and for this I have different textboxes called tbName1, tbName2 etc. Is it possible to use a variable in the textboxname? E.G. tbName[variable].Text

newUsers.Add(new ClassLibrary.UserClass
(
    "AAAAAAAA",
    tbName[variable].Text,    //Is it possible to do something like this?
    " ",
    tbLastname[variable].Text,
    tbEmail[variable].Text,
    " ",
    "0497111111",
    "0611111111",
    "USER"
));
2

There are 2 best solutions below

0
On

I'm afraid you won't be able to declare a variable on runtime as all variables have to be declared before compilation.

0
On

If understand your requirements correctly, you have a variable called "variable", which is of type Integer and depending of the value of this variable you want to get the Text property of different textboxes which are named after the same schema, but with incrementing integer-suffix. You could solve this via reflection, like this:

var tbNameX = (TextBox)this.GetType().GetProperty(tbName + variable).GetValue(this, null);
var tbLastnameX = (TextBox)this.GetType().GetProperty(tbLastname + variable).GetValue(this, null);
var tbEmailX = (TextBox)this.GetType().GetProperty(tbEmail + variable).GetValue(this, null);

newUsers.Add(new ClassLibrary.UserClass
(
    "AAAAAAAA",
    tbNameX.Text,    //Is it possible to do something like this?
    " ",
    tbNameX.Text,
    tbEmailX.Text,
    " ",
    "0497111111",
    "0611111111",
    "USER"
));

This requires a very strict naming on your textboxes, what makes it very vulnerable to mistakes. I don't recommend this for production use, but it should work.