Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert variable to a string of it's name

Status
Not open for further replies.

dgerdner

Programmer
Mar 30, 2005
41
0
0
US
Let's say I have:

string FirstName = "JOHN"

I'd like to set another string to the variable's name, "FirstName". Is there a c# method for this?

 
So you want to address the variable via a name?

Put that variable into a Hashtable (key/value pair) and address it that way.

Hashtable varhash = new Hashtable();

varhash.Add("FirstName", FirstName);

Then retrieve the variable via:

string firstname = (string)varhash["FirstName"];
 
Also, if you need the variable's name to be a string somewhere else, you could also use reflection.

----------------------------------------

TWljcm8kb2Z0J3MgIzEgRmFuIQ==
 
Well, ultimately what I'd like to accomplish is to avoid using the variable name in quotes. As some background, I find myself having to bind a lot of variables to textboxes on my forms, so I keep repeating code such as:

txtBox1.DataBindings.Add("Text", myTable, "MyColumn");

The problem here is that this can compile clean even if "MyColumn" is not spelled correctly, so the error is not discovered until run time. I'd rather be able to creating a binding method of my own, to which I can parse the variable to its name:

private void BindText(TextBox tb, String MyTable.MyColumn)
{
string s1 = getthecolumnname(MyTable.MyColumn)
tb.DataBindings.Add("Text", MyTable, s2)
}

This way if it compiles clean I know it's good.
 
>>Also, if you need the variable's name to be a string somewhere else, you could also use reflection. <<

Somebody else mentioned this, but I have only used reflection once before and don't know where to look for this particular item.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top