5

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

3 Answers 3

4

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";
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Controls has no Where method for me
2

An easier way is to do something like this:

string TMT = "myButton";    
// later in the code ...
(Controls[TMT] as Button).Text = "Hullo";

for instance.

3 Comments

It works just fine ... there are two overloads - one for ints and one for strings
If you are 100% sure that this.Controls contains specified name, you can cast type instead of operator as: ((Button)Controls["myButton"]).Text. But it's better to check everything
It is not working, it throws exception of null reference exception
1

You can do something like this:

        foreach (var c in this.Controls)
        {
            if (c is Label)
            {
                var x = (Label)c;
                if (x.Name == "label1")
                {
                    x.Text = "WE FOUND YOU";
                    break;
                }
            }
        }

However, best practice is to avoid such cases ... If you could speculate a bit more why you need this, there will probably be a better solution.

--edit:thanks for noticing that is/typeof ..

2 Comments

i have string arr[4] that contain "l1,l2,l3,l4" - and i need to read the text that in the label that named l1,l2,l3,l4. how do to it ? i try: ((control)arr[1].tostring()).text - but get error
You should use operator is instead of types comparison. Also should break on search success..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.