Does C# have a way to do something like the EVAL() function in Jav

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am wondering if anyone has done something like this? I want to find a label
based on the passed in information. It would be awesome to find something
like this:

private void myvoid (int i)
{
string lbl = "label" + i;
Label mylabel = (Label)lbl;

lbl.Text = "I have found the label on my form by this method!";
}

Anyone got a method?
Thanks!
 
Rob,

There is, but it isn't easy. It would basically require you to create
complete class definitions in code, and then compile them at runtime and
access them. If the classes don't implement some sort of interface, then
you are going to have to use Reflection to get all of your results.

All in all, I would recommend against trying to do this. What are you
trying to do?
 
Is something like that you want??


private object FindObject (string strObjectName, string strObjectType)
{
foreach (Control controlObj in this.Controls)
{
if ((controlObj.GetType().ToString() == strObjectType) && (controlObj.Name
== strObjectName))
{
return controlObj;
}
}
return null;
}

private void button1_Click(object sender, System.EventArgs e)
{
object obj = FindObject (textBox1.Text, "System.Windows.Forms.Label");
if (obj != null)
{
MessageBox.Show(((Label)obj).Text);
}
else
{
MessageBox.Show("object not found");
}
}
 
Well Done Daniel! Well done!

I wanted to see if I could set this object to the passed in string without
an iteration through the controls array, but it looks like it's the only way.

Thanks for the sample code. That was fun.

Cheers!

Rob

P.S. Interesting that the MVP goes way out of the way to do something fairly
simple here... Hmmmmmmm...
 
If you know the ID of the control you are looking for you do not need to
iterate through the controls collection.

There is a FindControl method that does this for you.

Mike Hanson
MCSD, MCSE+I, MCDBA, SCP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top