简体   繁体   中英

Reference an object's property by a string (or integer) that contains specified part of the object's name - C#

For example I have a method that returns the value "4"... My button's name is " b4 ". I want depending on the number that the method returns to change the Text property of that b "X". Eeasiest way to do it in C#. I am a beginner so please explain it well... I know this may be a duplicate post. But I didn't understand the answers in all similar posts. The code's layout is something like this:

I have an array of five numbers (eg "int[] rnum = {1, 6, 7, 3, 8}")... I also have 5 buttons that are supposed to get disabled depending on the integers given in the array... I have 25 buttons and their names are as follows "b1, b2, b3, b4.... etc.". So what is the easiest way to change a button's "Enabled" property by referencing the button object's name with the integers given in the array... For example the rnum[1] = 6 ==> b6.Enabled = false... I know I can make a switch statement but if there are lots of buttons how can I automate this?

As @Alex K. mentioned

public Button GetButtonByIndex(int index)
{
  return (Button)this.Controls.Find("b" + index, true).FirstOrDefault();
}

then GetButtonByIndex(1) will return b1 , etc.

You can do it using reflection. here is an example:

class Foo
{
    public int Bar1 { get; set; }
    public int Bar2 { get; set; }
    public Foo()
    {
        Bar1 = 2;
        Bar2 = 3;
    }
    public int GetBar(int barNum) //return type should be Button for you
    {
        PropertyInfo i = this.GetType().GetProperty("Bar"+barNum);
        if (i == null)
            throw new Exception("Bar" + barNum + " does not exist");
        return (int)i.GetValue(this); //you should cast to Button instead of int
    }
}

and Main:

class Program
{
    static void Main(string[] args)
    {
        Foo f = new Foo();
        for (int i = 1; i <= 3; i++)
            try
            {
                Console.WriteLine(f.GetBar(i));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        Console.ReadLine();
    }
}

The output will be:

2
3
Bar3 does not exist

note that while i printed the result of foo.GetBar(i) , you could in your case do something like that: foo.GetButton(i).Enabled = false;

While looking for buttons inside Controls (recursively or of known container) will works, much easier solution (in general) is this

var buttons = new[] {b1, b2, b3, b4, b5 }; // can be a field initialized in form constructor
buttons[number - 1].Text = "lalala"; // number is from 1 to 5

If you don't want to convert received number to index , then you can add null as first element into array.

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