开发者

C# WinForms / How to access the controls of the form containing a custom control?

Let's say I got a CustomListView control added into MainForm.

// CustomListView.cs

class CustomListView : ListView
{
    public CustomListView()
    {
        Ite开发者_运维百科mActivate += new EventHandler(ItemActivateEvent);
    }

    private void ItemActivateEvent(object sender, EventArgs e)
    {
        // update label in the parent form
    }
}

How can I access MainForm's other controls from there?


It would be easier to create the EventHandler from within the MainForm. That way you can very easily control your CustomListView Control and also your MainForm Control from with your MainForm.

Something like this:

MAINFORM.CS:

private void button1_Click(object sender, EventArgs e)
{
    // Creates and displays the custom control on your MainForm and 
    //     attaches an event to it.

    CustomListViewControl lv = new CustomListViewControl();
    this.Controls.Add(lv);

    lv.ItemActivate += new EventHandler(ItemActivateEvent);
}

void ItemActivate(object sender, EventArgs e)
{
    // Do some stuff with MainForm or its child controls in here.

    this.Text = "I am uber awesome";
    this.Hide();



}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜