gempir
gempir

Reputation: 1911

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}

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

Upvotes: 0

Views: 618

Answers (5)

Peter Huber
Peter Huber

Reputation: 3312

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.

Upvotes: 0

Maciej Los
Maciej Los

Reputation: 8591

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?

Upvotes: 0

Abdellah OUMGHAR
Abdellah OUMGHAR

Reputation: 3755

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;
}

Upvotes: 0

Mostafiz
Mostafiz

Reputation: 7352

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
                 }

              }
        }
    }

Upvotes: 0

Avi Turner
Avi Turner

Reputation: 10456

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;...

Upvotes: 1

Related Questions