简体   繁体   中英

Accessing variables dynamically in C#

I have tons of Buttons named like this x0y1

How do I access the variable name dynamically so I could loop all names by xiy1 or so.

in PHP it would be like ${"myString" . $randomvar} ${"myString" . $randomvar}

I can't use a list or array because the the button already exist defined through the xaml

You can use:

var textbox = 
   this.Controls.OfType<TextBox>().Where(txb => txb.Name == "myString").FirstOrDefault();

This assumes you are in the context of your form ( this.Controls ).

And of course, don't forget to add using System.Linq; ...

You can get all the textbox using this method

void AllTextBox(System.Windows.Forms.Control.ControlCollection ctrls)
    {
       foreach (Control ctrl in ctrls)
       {
          if (ctrl is TextBox)
              {
                 if (ctrl.Name == "textBox1")
                 {
                    // do your stuf with textbox
                 }

              }
        }
    }

You can create function that return control by name :

Control GetControlByName(string Name)
{
    foreach(Control control in this.Controls)
        if(c.Name == Name) return control ;

    return null;
}

or Function with a specific control like that :

Button GetButtonByName(string Name)
{
    foreach (Control c in this.Controls.OfType<Button>())
        if (c.Name == Name) return c;

    return null;
}

For wpf project...

Let's say you have a grid named MyGrid and there's lot of buttons on it. You want to refer to the button named x0y1 :

var btn = MyGrid.Children.OfType<Button>().Where(x=>x.Name=="x0y1");

Note: above code should work for flat structure (one level deep only).

You can achieve the same by using code provided in this thread: How can I find WPF controls by name or type?

Just call FindName("elementName"). FindName searches through all child elements of a FrameworkElement. To access any button by its name as string in a window, call the FindName() method of the window !

If your code is in a class inheriting from Window, just use:

Button button = (Button)FindName("xiy1");

If you write the code in a class not inheriting from Window but FrameworkElement, which is unlikely, use:

Window window = Window.GetWindow(this);
Button button = (Button)window.FindName("xiy1");

Check the MSDN documentation about Namescopes for more information about limitations.

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