开发者

Changing the BackColor of my custom UserControl - help!

(lol)

I have a panel on Form1. I'm going to add several instances of my custom usercontrol MovieItem to that panel.

To do this I'm going:

panel1.Controls.Add(objMovieItem);

Now, within the MovieItem.cs code I'm adding the .Click events of everything inside the UserControl so that whenever a user clicks ANYWHERE inside my Us开发者_如何学JAVAerControl, it's background color changes.

Here's the problem:

I have about 10 instances of the UserControl on Form1 (inside of the Panel1 of course). How can I put the BackColor of the selected one to lightblue, and all of the others back to the default color?

Here's my code:

private void SearchMovie()
{
     //All this does is create an instance of the UserControl and add it to Panel1.
     MovieItem NewMovie = new MovieItem();
     NewMovie.SearchMovie(txtSearch.Text);
     panel1.Controls.Add(NewMovie);
}

Now, inside of my user controls code:

private void MovieItem_Click(object sender, EventArgs e)
    {            
        MainSearchForm MainFormObject = new MainSearchForm();

        foreach (Control y in MainFormObject.Controls["panel1"].Controls)
        {
            if (y is UserControl)
            {
                if (y is MovieItem)
                {                        
                    y.BackColor = Color.White;
                }                    
            }
        }

        this.BackColor = Color.LightBlue;
    }

Here's what happens. The click events are 100% OK. Works as intended. When I click on an object of my UserControl it changes color correctly. But the other don't change back to default. What am I doing wrong.

Thanks SO.


In the handler, you create a new MainSearchForm object, and then set its controls to white, so you aren't affecting the form you are displaying.

Use this.Parent to find the parent panel, or use a static variable to hold a reference to your mainForm (or etc).

as in:

private void MovieItem_Click(object sender, EventArgs e)
{
    foreach (Control y in this.Parent.Controls)
    {
        if (y is MovieItem && y != this)
            y.BackColor = Color.White;
    }
    this.BackColor = Color.LightBlue;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜