Balram
Balram

Reputation: 190

How to use string as variable name in c#

am having a viewstate which pertains value like:

string temp; ViewState["temp"] = dc.ColumnName.ToString();

This returns weekdays like: Monday,tuesday,wednesday etc

Now am using this value here:

string a = "txt" + ViewState["temp"].ToString();
TextBox a = new TextBox();

But it gives me error

Cannot implicitly convert type 'System.Web.UI.WebControls.Textbox' to 'string'

I want textbox variable name like txtmonday,txttuesday dynamically. Is there any way that I can assign variable name???

Upvotes: 0

Views: 2062

Answers (2)

Adil
Adil

Reputation: 148110

You can not declare objects at runtime they way you art trying. You can store the week days in array / List<T> starting Monday at index 0 and Sunday at index 6, You can give id of element with the string name you want.

List<TextBox> weekList = new List<TextBox>();
weekList.Add(new TextBox());
weekList[0].ID  =  "txt" + ViewState["temp"].ToString();

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499800

No, you can't. At least not without reflection, and you shouldn't be using reflection here. Variables in C# are a compile-time concept. (Even with reflection, it'll only work for fields, not for local variables.)

If you want a collection of values, use a collection... e.g. a List<T> or a Dictionary<TKey, TValue>. So for example, you could have a List<TextBox> (which is accessed by index) or a Dictionary<string, TextBox> which is accessed by string key ("monday", "tuesday" or whatever you want).

If you're only actually creating a single TextBox, what does it matter what the variable name is? Just use:

TextBox textBox = new TextBox();
// Do appropriate things with the TextBox, possibly using ViewState

The variable name just gives you a way of referring to the variable. That's all it's there for. The object you create doesn't know anything about which variables (if any) contain references to it.

Upvotes: 3

Related Questions