简体   繁体   中英

adding winform user control event in c#

I am learning c# at the moment.

I have setup a winform user control (called aUC) with 1 button (called simpleButton1) in vb I can do the following.

dim aUC1 as aUC = new aUC()

'load user control to form
Me.controls.clear()
Me.controls.Add(aUC1)

' attach button event
AddHandler aUC1.simpleButton1.Click, AddressOf aUCButton_Click

so I try to do the same on c#

aUC aUC1 = new aUC();

' load user control to form
this.Controls.Clear();
this.Controls.Add(aUC1);

aUC1.simpleButton1.Click += aUCBtn_Click;

when I compile I get

aUC.simpleButton1 is inaccessible due to its protection level.

I notice when I look at the designer code on user control

in vb it says

Friend WithEvents SimpleButton1 As DevExpress.XtraEditors.SimpleButton

in c# it says

private DevExpress.XtraEditors.SimpleButton simpleButton1;

when I change from private to public on user control design generated code it works ok.

I just wondering if this standard practice in c# to hook user control event on main form is to change the control from private to public; or there is a better way/best practice for c#, I prefer not to changing the code on the design generated code in case I accidentally stuff it up.

Thank you.

Regards

  • Haris -

As soon as You want to access a button from another class you should change the access modifier to public from the designer there is no other way

but I will advise you to learn WPF instead of Winforms

As suggested by Caius,

I create a button click call back on the user control and expose it public event

public partial class aUC : UserControl
{
    public EventHandler aUCBtn_Click;

    public aUC()
    {
        InitializeComponent();
    }

    private void simpleButton1_Click(object sender, EventArgs e)
    {
        if (aUCBtn_Click != null)
            aUCBtn_Click(sender, e); // send event to public event
    }
}

and on the main form consume that public event

public Form1()
{
    InitializeComponent();

    aUC aUC1 = new aUC();
    this.Controls.Clear();
    this.Controls.Add(aUC1);

    aUC1.aUCBtn_Click += aUC1_Click; // hook to user control event                       
}

private void aUC1_Click(object sender, EventArgs e)
{
    MessageBox.Show("btn click");
}

Thank you.

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