-2

I have a Windows Form (MainForm1) that contains a ToolStrip with a label in it (StatusLabel). MainForm1 also contains a User Control (UserControl1). The User Control contains a button (Button1). When Button1 is clicked it initializes a DataGridView, but that is not important.

When Button1 is clicked in UserControl1, I want to display text in the MainForms StatusLabel.

But I don't know how to do that from one UserControl to the MainForm.

The flow chart describes how I would like it to function.

Sinatr
  • 20,892
  • 15
  • 90
  • 319
  • Provide a way for `UserControl` to access text. There are many possibilities: public (static?) property of `MainForm` (accessible from anywhere), event of `UserControl` (form subscribe to it and change text when `UserControl` tell so), callback/interface passed to `UserControl` (e.g. as constructor parameter). – Sinatr Jun 13 '16 at 11:42
  • 2
    [How do I feed values to the statusStrip from a form control?](https://stackoverflow.com/questions/37483278/how-do-i-feed-values-to-the-statusstrip-from-a-form-control) – Reza Aghaei Jun 13 '16 at 11:45

1 Answers1

0

You can do this simply by creating an event in your User Control

public event EventHandler<string> MessageHasSent;
public void SendMessage(string message)
{
    EventHandler<string> ms =  MessageHasSent;
    if (ms!= null)
    {
         ms(this,message);
    }
}

And in every where in your class that you want Raise this event.In your case you want by clicking on button send message

public Button1_Click( object sender,EventArgs e)
{
     SendMessage("YourMessage");
}

And use it like other events.In your MainForm use this event of your UserControl .

public class MainForm:Form
{
    public MainForm()
    {
        UserControl1.MessageHasSent +=SetToolStripLabel;
    }
    public  SetToolStripLabel( object sender,string e)
    {
        //Set e to Label
    }
}
mohsen
  • 1,763
  • 3
  • 17
  • 55