1

Possible Duplicate:
Get access to parent control from user control - C#

I have btnMessage on my form Main, and I also have user control (uc).

When I click btnMessage, it opens the uc and also makes btnMessage.enabled = false. In uc, there's a button that's called btnExecute.

What I want is that when I click on btnExecute in uc, btnMessage in Main form will be disabled. How I can do this?

Here's the update code :

I'm using function in main.cs

    public Main()
    {
        InitializeComponent();
        formFunctionPointer += new functioncall(buttonHideorEnabled);
        ucMessageTarget.userFunctionPointer = formFunctionPointer;
    }

    public delegate void functioncall(bool _status);

    private event functioncall formFunctionPointer;

    public void buttonHideorEnabled(bool _status)
    {
        btnMessageTarget.Enabled = _status;
    }

and in uc.cs :

    public static string agentName = UtilitiesToolkit.agentMessageTarget;
    public static string strn;

    public UcMessageTarget(string str)
    {
        InitializeComponent();
        strn = str;
    }

    public Delegate userControlPointer;
    public Delegate userFunctionPointer;
    private void btnExecute_Click(object sender, EventArgs e)
    {
       btnExecute.enabled = false;
       userFunctionPointer.DynamicInvoke(false);
       //I want btnMessage in Main form also disabled, please tell me how
    }

but, still, didn't work. when I compile, I have error in main, in this line :

    public Main()
    {
        InitializeComponent();
        formFunctionPointer += new functioncall(buttonHideorEnabled);
        ucMessageTarget.userFunctionPointer = formFunctionPointer;
    }

said, that

object reference is not set to an instance of object (in ucMessageTarget.userFunctionPointer = formFunctionPointer;).

please help.

Community
  • 1
  • 1

2 Answers2

1

You can programmatically subscribe to event handlers in the code-behind, so add one to the "parent" form for the "child" form's button:

uc.btnExecute.Click += new EventHandler(name_of_method_to_handle_click_event);

The only requirement is that the control be public so that the parent form can access it.

Tieson T.
  • 20,774
  • 6
  • 77
  • 92
0

What I would rather do is raise an event from the user control, which the main form listens to, and then disable the button in this event handler.

Something like User Control Events in VB and C#

This would avoid the user control having to "know" anything about the caller (parent form).

Search a little on SO, you will find a lot of examples for raising events from user controls.

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284