简体   繁体   中英

How to visible label with other name in c#

I have labels and their name like label1,label2,... etc. and I know how to visible label like label1.visible = true But what I want to do is make some of them visible with other name like the code below

            for (i = 0; i < ceksayisi*2; i++)
            {
                num = i;
                labelname = "label" + num;
                labelname.visible = true;
            }

The code gives me 'string' does not contain a definition for 'visible' and no extension method 'visible' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

You are doing a classical mistake here. The Droid you are looking for are arrays and other collections. You can not build variable names like that outside of some really weakly typed langauges.

No .NET Langauge is weakly typed. And that is by design.

To achieve this You should use Dictionary here.

Dictionary<string, Label> keyValuePairs = new Dictionary<string, Label>();

And add your label in the dictionary with according keys

keyValuePairs.Add("label_" + num, label1);

you can access your labels like

Label lbl = keyValuePairs["label" + num];

then you can play with this lbl

lbl.Visible = false;

Since that is a case-sensitive programming language, it won't work with labelname.visible = true; but you have to change that piece of code with: labelname.Visible = true;

Edit:

Might have misunderstood, if you're trying to Show/Hide a label that you don't know the name dynamically, you may try doing something like this:

for(int i = 0; i < ceksayisi*2; i++)
{
    num = i;
    Label labelname = (Label) Controls.Find("label" + num, true).FirstOrDefault();
    labelname.Visible = true;
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM