Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to control?

i have string MyText that hold "L1"

i have label control that his name is "L1"

is there any way to read label L1 using MyText ?

something like: TMT = MyText.Text

or: TMT = ((Control)MyText.ToString()).Text;

thanks in advance

like image 992
Gold Avatar asked May 30 '10 13:05

Gold


People also ask

How do you convert a value to a string?

The String() method converts a value to a string.


1 Answers

Find a control with specified name:

var arr = this.Controls.Where(c => c.Name == "Name");
var c = arr.FirstOrDefault();

or search within controls of specified type:

var arr = this.Controls.OfType<Label>();
var c = arr.FirstOrDefault();

Edit:

if you have an array of control names you can find them:

var names = new[] { "C1", "C2", "C3" };

// search for specified names only within textboxes
var controls = this.Controls
    .OfType<TextBox>()
    .Where(c => names.Contains(c.Name));

// put the search result into a Dictionary<TextBox, string>
var dic = controls.ToDictionary(k => k, v => v.Text); 

(everything above requires .NET 3.5)

If you don have it, you can do next:

Control[] controls = this.Controls.Find("MyControl1");
if(controls.Lenght == 1) // 0 means not found, more - there are several controls with the same name
{
    TextBox control = controls[0] as TextBox;
    if(control != null)
    {
        control.Text = "Hello";
    }
}
like image 91
abatishchev Avatar answered Oct 21 '22 07:10

abatishchev