开发者

Get a control handle by its name

开发者 https://www.devze.com 2023-03-10 00:57 出处:网络
I have a UserControl with several PictureBoxes on it. These are the onl开发者_Python百科y controls on the UserControl. All the PictureBoxes are all named \'pbx\' plus a color such as \'pbxGrey\' or \'

I have a UserControl with several PictureBoxes on it. These are the onl开发者_Python百科y controls on the UserControl. All the PictureBoxes are all named 'pbx' plus a color such as 'pbxGrey' or 'pbxBlack'. I have a method that selects one of the PictureBoxes and changes the BorderStyle to represent that it has been selected. I have tried to use the this.Controls["pbx" + color] method but there is no property for setting the BorderStyle.

    public void SelectColor(string color)
    {
        ClearBorderSyles();
        this.Controls["pbx" + color]. //No BorderStyle property
        SelectedColor = color;
    }

I have also tried this to get at the same property:

    public void SelectColor(string color)
    {
        ClearBorderSyles();
        Picturebox handle = new PictureBox();
        handle = this.Controls["pbx" + color];
        SelectedColor = color;
    }

In this sample VS says that I can't implcitly convert a Control to a PictureBox. So what I need to know is how do you get a handle on the control so I can change the BorderStyle? Please answer in C#, or in VB if necessary. Thank You.


You should try using the casting operator:

Also, you shouldn't assign handle a new object if you're planning to throw it away on the next line:

I would suggest something like:

if(this.Controls["pbx" + color] is PictureBox)
{
   PictureBox handle = this.Controls["pbx" + color] as PictureBox;
}

or:

using(PictureBox handle = this.Controls["pbx" + color] as PictureBox)
{
     ...
}

Of course, you should check that the control isn't null before trying to assign or use, etc. But you get the idea.

0

精彩评论

暂无评论...
验证码 换一张
取 消