call event from form2 in form1 - c#

hi
call event from form2 in form1?
for example :
The following code into form2 :
private void Form2_Load(object sender, EventArgs e)
{
MessageBox.Show("http://stackoverflow.com");
}
What to write in a form1?

Why are you wanting to call the event? Will you know the sender and the Event Args?
Why don't you just create a public method in Form2 that Form1 is able to see?

how about form2.Form2_Load(this, null)

You can't call private members of a class from outside it.
You can change the accessibility to internal, which will make it visible within the assembly - if your form1 is in the same assembly.
Alternatively you can make it a public method, which would make it globally accessible.
However, you shouldn't call event handlers in such a manner - they are supposed to handle events that the declaring class raises.
For the sample code you gave, a better solution would be to create a public or internal method that can be called from this event handler:
private void Form2_Load(object sender, EventArgs e)
{
MyMethod();
}
public MyMethod()
{
MessageBox.Show("http://stackoverflow.com");
}
In order to call this method from form1, it needs to know about form2:
// in form1
Form frm2 = new Form2();
frm2.MyMethod();

You can't raise an Event from outside a class.
The convention is that you call a OnEventname method in the class. Usually this method is protected (can't only accessed from the class itself or others that inherit from it)
// in form1
private void Method1()
{
using (var form2 = new Form2())
{
form2.Show();
form2.RaiseLoadEvent(EventArgs.Empty);
}
}
// Create this method in form2
public void RaiseLoadEvent(EventArgs e)
{
OnLoad(this, e);
}
// The OnLoad method already exists in form 2
// But it usually looks like this
protected void OnLoad(EventArgs e)
{
var eh = LoadEventHandler;
if (eh != null)
{
eh(this, e);
}
}
But I don't suggest to raise the LoadEvent, because It is raised only once after the creation of the form. More usual is to react to the Load event to modify the form.
privat void Method1()
{
using (var form2 = new Form2())
{
// Add Event Handler
form2.Load += new EventHandler(form2_Load);
form2.ShowDialog();
}
// Allways remove Event Handler to avoid memory leaks
form2.Load -= new EventHandler(form2_Load);
}
private void form2_Load(object sender, EventArgs e)
{
form2.Text = "Hello from form1";
}

Form1 (the event publisher) should expose a separate, public event property for Form2 (the subscriber) to subscribe to.
For example: the form publishing the event will look like this:
public partial class Publisher : Form
{
public event PostUpdateHandler OnPostUpdate;
public Publisher()
{
InitializeComponent();
new Subscriber(this).Show();
}
private void button1_Click(object sender, EventArgs e)
{
if (OnPostUpdate != null)
{
OnPostUpdate(new PostUpdateArgs(textBox1.Text));
}
}
}
public delegate void PostUpdateHandler(PostUpdateArgs args);
public class PostUpdateArgs : EventArgs
{
public string UpdateText;
public PostUpdateArgs(string s)
{
UpdateText = s;
}
}
The subscribing form looks like this:
public partial class Subscriber : Form
{
public Subscriber()
{
InitializeComponent();
}
public Subscriber(Publisher publisher) : this()
{
publisher.OnPostUpdate += new PostUpdateHandler(publisher_OnPostUpdate);
}
private void publisher_OnPostUpdate(PostUpdateArgs args)
{
this.Form2_Load(null, null);
}
private void Subscriber_FormClosed(object sender, FormClosedEventArgs e)
{
this.Dispose();
}
private void Form2_Load(object sender, EventArgs e)
{
MessageBox.Show("http://stackoverflow.com");
}
}
When the user presses button1 on the publishing form, the subscribing form will execute the code associated with the delegate, resulting in a message box popping up with the message http://stackoverflow.com.

Related

How do I can call event from usercontrol to main form

I have a userControl and I've a button there, I'd like to call event when I'm clicking on the button in my main form from userControl. I do this:
UserControl
public UserControlerConstructor()
{
_button.Click += new EventHandler(OnButtonClicked);
}
public delegate void ButtonClickedEventHandler(object sender, EventArgs e);
public event ButtonClickedEventHandler OnUserControlButtonClicked;
private void OnButtonClicked(object sender, EventArgs e)
{
// Delegate the event to the caller
if (OnUserControlButtonClicked != null)
OnUserControlButtonClicked(this, e);
}
Form
public Form1()
{
userControlInstance.OnUserControlButtonClicked += new EventHandler(OnUCButtonClicked);
}
private void OnUCButtonClicked(object sender, EventArgs e)
{
throw new NotImplementedException();
}
It doesn't work because when I click in the form do nothing in the form code, but it does in userControl code. But I'd like to do in form code. I don't know how to call event from userControl to the form.
Well now I don't know if you're explicity want to use the delegate, no? If not, why don't you just do:
public Form1()
{
userControlInstance._button.Click += OnUCButtonClicked;
}
private void OnUCButtonClicked(object sender, EventArgs e)
{
throw new NotImplementedException();
}
up to now your code does not compile. You are using the wrong event handler type. It should show the following compiler error:
EventHandler cannot be converted to ButtonClickedEventHandler
Do the following steps:
1) put the declaration of the delegate outside of the class UserControlerConstructor:
public delegate void ButtonClickedEventHandler(object sender, EventArgs e);
public partial class UserControlerConstructor: UserControl
{
1) then change the type of the handler when registering the event in Form:
public Form1()
{
userControlInstance.OnUserControlButtonClicked += new ButtonClickedEventHandler(OnUCButtonClicked);
}
This way it should work

c# execute a method from Form in the MainForm [duplicate]

I am working with windowsFrom in c#. I am trying to call mainfrom method in one of the from in user control.
I have mainfrom like this
namespace Project
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
public void TempCommand()
{
StartTemp();
}
}
}
I have the button click in the user control. When i click that button then it will open another form. I have the code like this in the user control.
private TempCalib _tempCalib = new TempCalib();
private void calibBtn_Click(object sender, EventArgs e)
{
_tempCalib.Show();
}
it will open another from and i have one button in that from. I need to call mainfrom method when i click "Ok" button in this from.
namespace Project
{
public partial class TempCalib : Form
{
public TempCalib()
{
InitializeComponent();
}
private void OkButton_Click(object sender, EventArgs e)
{
// I need to call the mainfrom "TempCommand" method here.
this.Hide();
}
}
}
Can anyone help me how to do this.
Thanks.
Quick answer
Just add a reference to the primary form in your secondary form:
public partial class TempCalib : Form
{
private MainForm _main
public TempCalib(MainForm main) : this()
{
_main = main;
}
/// Other stuffs
}
Then assign value when you construct your secondary form:
private TempCalib _tempCalib;
private void calibBtn_Click(object sender, EventArgs e)
{
if (_tempCalib == null)
_tempCalib = new TempCalib(this);
_tempCalib.Show();
}
If calibBtn_Click isn't inside MainForm (but it's inside a UserControl on it) then you can replace _tempCalib initialization with:
_tempCalib = new TempCalib((MainWindow)FindForm());
You'll be then able to call the primary form:
private void OkButton_Click(object sender, EventArgs e)
{
_main.TempCommand();
this.Hide();
}
Notes: this is just one option, you may create a property to hold MainForm reference (so secondary form can be reused and it'll be more designer friendly) moreover TempCalib is not an UserControl but a Form (pretty raw but for an UserControl you may just check its parent Form and cast it to proper type).
Improvements
Such kind of references are often an alert. Usually UI components shouldn't not be so coupled and a public Form's method to perform something very often is the signal that you have too much logic in your Form. How to improve this?
1. DECOUPLE CONTROLS. Well a first step may be to decouple them a little bit, just add an event in TempCalib and make MainForm its receiver:
public partial class TempCalib : Form
{
public event EventHandler SomethingMustBeDone;
private void OkButton_Click(object sender, EventArgs e)
{
OnSomethingMustBeDone(EventArgs.Empty); / TO DO
this.Hide();
}
}
Then in MainForm:
private TempCalib _tempCalib;
private void calibBtn_Click(object sender, EventArgs e)
{
if (_tempCalib == null)
{
_tempCalib = new TempCalib();
_tempCalib.SomethingMustBeDone += _tempCalib_SomethingMustBeDone;
// In _tempCalib_SomethingMustBeDone you'll invoke proper member
// and possibly hide _tempCalib (remove it from OkButton_Click)
}
_tempCalib.Show();
}
2. DECOUPLE LOGIC FROM CONTROLS. UI changes pretty often, logic not (and when it changes probably isn't in parallel with UI). This is just the first step (now TempCalib isn't aware of who will use it). Next step (to be performed when too much things happen inside your form) is to remove this kind of logic from the form itself. Little example (very raw), keep TempCalib as before (with the event) and change MainForm to be passive:
public partial class MainForm : Form
{
public event EventHandler Calibrate;
protected virtual void OnCalibrate(EventArgs e)
{
// TODO
}
}
Now let's create a class to control the flow and logic:
public class MyTaskController
{
private MainForm _main;
private TempCalib _tempCalib;
public void Start()
{
_main = new MainForm();
_main.Calibrate += OnCalibrationRequested;
_main.Show(); // Or whatever else
}
private void OnCalibrationRequested(object sender, EventArgs e)
{
if (_tempCalib == null)
{
_tempCalib = new TempCalib();
_tempCalib.SomethingMustBeDone += OnSomethingMustBeDone();
}
_tempCalib.Show();
}
private OnSomethingMustBeDone(object sender, EventArgs e)
{
// Perform the task here then hide calibration window
_tempCalib.Hide();
}
}
Yes, you'll need to write much more code but this will decouple logic (what to do as response to an action, for example) from UI itself. When program grows up this will help you to change UI as needed keeping logic unaware of that (and in one well defined place). I don't even mention that this will allow you to use different resources (people) to write logic and UI (or to reuse logic for different UI, WinForms and WPF, for example). Anyway IMO the most obvious and well repaid benefit is...readability: you'll always know where logic is and where UI management is, no search, no confusion, no mistakes.
3. DECOUPLE LOGIC FROM IMPLEMENTATION. Again you have more steps to perform (when needed). Your controller is still aware of concrete types (MainForm and TempCalib). In case you need to select a different form at run-time (for example to have a complex interface and a simplified one or to use dependency injection) then you have to decouple controller using interfaces. Just an example:
public interface IUiWindow
{
void Show();
void Hide();
}
public interface IMainWindow : IUiWindow
{
event EventHandler Calibrate;
}
public interface ICalibrationWindow : IUiWindow
{
event EventHandler SomethingMustBeDone;
}
You could use a custom event that is declared in your UserControl. Then your form needs to handle this event and call the method you want to call. If you let the UserControl access your form, you are hard-linking both with each other which decreases reusability of your UserControl.
For example, in TempCalib:
public delegate void OkClickedHandler(object sender, EventArgs e);
public event OkClickedHandler OkClicked;
private void OkButton_Click(object sender, EventArgs e)
{
// Make sure someone is listening to event
if (OkClicked == null) return;
OkClicked(sender, e);
this.Hide();
}
in your mainform:
private void Mainform_Load(object sender, EventArgs e)
{
_tempCalib.OkClicked += CalibOkClicked;
}
private void CalibOkClicked(Object sender, EventArgs e)
{
StartTemp();
}
You create an event in your usercontrol and subscribe to this in the mainform.
That is the usual way.
Form1 Code:
UserControl1 myusercontrol = new UserControl1();
public void TabClose(Object sender,EventArgs e)
{
int i = 0;
i = tabControl1.SelectedIndex;
tabControl1.TabPages.RemoveAt(i);
}
private void Form1_Load(object sender, EventArgs e)
{
myusercontrol.Dock = DockStyle.Fill;
TabPage myTabPage = new TabPage();
myTabPage.Text = "Student";
myTabPage.Controls.Add(myusercontrol);
tabControl1.TabPages.Add(myTabPage);
myusercontrol.OkClick += TabClose;
}
UserControl1 Code:
public delegate void OkClickedHandler(Object sender, EventArgs e);
public partial class UserControl1 : UserControl
{
public event OkClickedHandler OkClick;
public UserControl1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
if (OkClick == null) return;
OkClick(sender, e);
}
}
Try this:
From user control try this:
MainForm form = this.TopLevelControl as MainForm;
form.TempCommand();

How do i create an event in a mdi parent form and catch it in a child form

I've found a fair amount of information on this subject and stolen most of my current code from other threads on this forum but don't seem to be able to put it all together correctly. I've created a main form "Form1" that is a mdi container. I can create a child form "formStripChart" from a menu item on Form1. I'd like to fire my own event that gets fired every time a timer_tick handler fires in Form1 and catch my event in an event hander in formStripChart to update a chart control. I can see that Form1 is calling the "UpdateStatus" method but OnUpdateStatus is always null so the "UpdateStatus" event handler in formStripChart never gets called. Seems like I'm not doing whatever needs to be done in formStripChart to make Form1 realize someone is listening to the event but I haven't been able to figure out what.
Here's the relevant code in Form 1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public delegate void StatusUpdateHandler(object sender, ProgressEventArgs e);
public event StatusUpdateHandler OnUpdateStatus;
private static double depthValue = 0.0;
private static Random randomValue = new Random();
private void timerData_Tick(object sender, EventArgs e)
{
depthValue = depthValue + randomValue.NextDouble() - 0.5;
iusblEventArgs.xValue = 0.0;
iusblEventArgs.yValue = 0.0;
iusblEventArgs.zValue = depthValue;
iusblEventArgs.timeStamp = DateTime.Now;
ProgressEventArgs args = new ProgressEventArgs("test status");
UpdateStatus("sent from timerData_tick");
}
private void UpdateStatus(string status)
{
// Make sure someone is listening to event
if (OnUpdateStatus == null) return;
ProgressEventArgs args = new ProgressEventArgs(status);
OnUpdateStatus(this, args);
}
public class ProgressEventArgs : EventArgs
{
public string Status { get; private set; }
public ProgressEventArgs(string status)
{
Status = status;
}
}
private void btnGo_Click(object sender, EventArgs e)
{
timerData.Enabled = true;
}
and here's the relevant code in formStripChart
public partial class FormStripChart : Form
{
private Form1 form1;
public FormStripChart()
{
InitializeComponent();
form1 = new Form1();
form1.OnUpdateStatus += new Form1.StatusUpdateHandler(UpdateStatus);
}
private void UpdateStatus(object sender, Form1.ProgressEventArgs e)
{
Console.Write("Update the chart here");
}
}
Thanks for any help.
It might be easier to pass form1 to the constructor of your child form like this:
Public void FormStripChart(Form1 f)
{
form1 = f;
form1.OnUpdateStatus += new Form1.StatusUpdateHandler(UpdateStatus);
}
This way your child form knows what instance of the main form to use.

How to get string data in main form from second from, when button on second form is clicked in C# .net?

At first I thought that it won't be a problem for me, but now I can't figure it out. So,
when I click Button1 in main form, form2 opens. Form2 is simple numeric keyboard, that user can enter some data. On form2 is also Save. When user clicks it, entered value should pass to main form and from that moment some event must happen in main form, which contains data from form2. Could you please give me some example or any kind of help? Thanks!
// code from main form to create form2
private void button1_Click(object sender, EventArgs e)
{
// Create a new instance of the Form2 class
Form2 settingsForm = new Form2();
// Show the settings form
settingsForm.Show();
string val = settingsForm.ReturnValue1;
MessageBox.Show(val);
}
//button save on form2
private void button13_Click(object sender, EventArgs e)
{
this.ReturnValue1 = "Something";
this.ReturnValue2 = DateTime.Now.ToString(); //example
this.Close();
//after this, some event should happen in main form !
}
There is a lot of solutions to do what you want; but I think one of these will resolve your problem.
1- Simple and easy: use public properties in Form2, initialize them when buttonSave get clicked, and access them in Form1:
Form2:
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
YourDate = "something";
Close();
}
public object YourDate { get; private set; }
}
Form1:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
var f2 = new Form2();
f2.ShowDialog();
var data = f2.YourDate;
}
}
2- A better way, is using events which is more flexible and professional programming friendly:
Form2:
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
}
// create an event of Action<T> which T is your data-type. e.g. in this example I use an object.
public event Action<object> SaveClicked;
// create an event invocator, to invoke event whenever you want
protected virtual void OnSaveClicked(object data){
var handler = SaveClicked;
if (handler != null)
handler(data);
}
private void button1_Click(object sender, EventArgs e){
// prepare your data here, -object, or string, or int, or whatever it is
var data = PrepareYourDataHere;
// invoke the event
OnSaveClicked(data);
Close();
}
}
Form1:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
// create an instance of Form2
var f2 = new Form2();
// add an event listener to SaveClicked event -which we have declared it in Form2
f2.SaveClicked += f2_SaveClicked;
f2.Show();
// or: f2.ShowDialog();
}
void f2_SaveClicked(object obj) {
// get data and use it here...
// any data which you pass in Form2.OnSaveClicked method, will be accessible here
}
}
UPDATE:
If you want to fire some events in form1, just after form2 closed, you can simply add a listener to Form2.FormClosed event:
// code from main form to create form2
private void button1_Click(object sender, EventArgs e) {
// Create a new instance of the Form2 class
Form2 settingsForm = new Form2();
settingsForm.FormClosed += SettingFormClosed;
// Show the settings form
settingsForm.Show();
string val = settingsForm.ReturnValue1;
MessageBox.Show(val);
}
void SettingFormClosed(object sender, FormClosedEventArgs e) {
// this method will be called automatically when form2 closed
}
here a sample how you can achieve this
//here I suppose that form1 is the mainform
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void UpdateMainForm(string updatedString)
{
//here you can update and invoke methods
//Once called you could raise events in your mainform
}
private void button1_Click(object sender, EventArgs e)
{
using (Form2 form2 = new Form2(this))
{
form2.ShowDialog();
}
}
}
Form2
public partial class Form2 : Form
{
private Form1 _mainForm1;
public Form2(Form1 mainForm1)
{
InitializeComponent();
_mainForm1 = mainForm1;
}
private void button1_Click(object sender, EventArgs e)
{
_mainForm1.UpdateMainForm( DateTime.Now.ToString());
}
}

Listening to Events in Main Form from Another Form in C#

I have an application that has a main form and uses an event handler to process incoming data and reflect the changes in various controls on the main form. This works fine.
I also have another form in the application. There can be multiple instances of this second form running at any given time.
What I'd like to do is have each instance of this second form listen to the event handler in the main form and update controls on its instance of the second form.
How would I do this?
Here's some sample code. I want to information from the_timer_Tick event handler to update each instance of SecondaryForm.
public partial class Form1 : Form
{
Timer the_timer = new Timer();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
the_timer.Tick += new EventHandler(the_timer_Tick);
the_timer.Interval = 2000;
the_timer.Enabled = true;
}
void the_timer_Tick(object sender, EventArgs e)
{
// I would like code in here to update all instances of SecondaryForm
// that happen to be open now.
MessageBox.Show("Timer ticked");
}
private void stop_timer_button_Click(object sender, EventArgs e)
{
the_timer.Enabled = false;
}
private void start_form_button_Click(object sender, EventArgs e)
{
SecondaryForm new_form = new SecondaryForm();
new_form.Show();
}
}
class SecondForm
{
private FirstForm firstForm;
public SecondForm()
{
InitializeComponent();
// this means unregistering on form closing, uncomment if is necessary (anonymous delegate)
//this.Form_Closing += delegate { firstForm.SomeEvent -= SecondForm_SomeMethod; };
}
public SecondaryForm(FirstForm form) : this()
{
this.firstForm = form;
firstForm.Timer.Tick += new EventHandler(Timer_Tick);
}
// make it public in case of external event handlers registration
private void Timer_Tick(object sender, EventArgs e)
{
// now you can access firstForm or it's timer here
}
}
class FirstForm
{
public Timer Timer
{
get
{
return this.the_timerl
}
}
public FirstForm()
{
InitializeComponent();
}
private void Button_Click(object sender, EventArgs e)
{
new SecondForm(this).ShowDialog(); // in case of internal event handlers registration (in constructor)
// or
SecondForm secondForm = new SecondForm(this);
the_timer.Tick += new EventHandler(secondForm.Timer_tick); // that method must be public
}
Consider using loosely coupled events. This will allow you to couple the classes in such a way that they never have to be directly aware of each other. The Unity application block comes with an extension called EventBroker that makes this very simple.
Here's a little lick of the sugar:
public static class EVENTS
{
public const string UPDATE_TICKED = "event://Form1/Ticked";
}
public partial class Form1 : Form
{
[Publishes(EVENTS.UPDATE_TICKED)]
public event EventHandler Ticked;
void the_timer_Tick(object sender, EventArgs e)
{
// I would like code in here to update all instances of SecondaryForm
// that happen to be open now.
MessageBox.Show("Timer ticked");
OnTicked();
}
protected virtual void OnTicked()
{
if (Ticked == null) return;
Ticked(this, e);
}
}
public partial class SecondaryForm : Form
{
[SubscribesTo(EVENTS.UPDATE_TICKED)]
private void Form1_Ticked(object sender, EventHandler e)
{
// code to handle tick in SecondaryForm
}
}
Now if you construct both of these classes using Unity, they will automatically be wired together.
Update
Newer solutions use message bus to handle loosely coupled events. See http://masstransit-project.com/ or http://nimbusapi.github.io/ as examples.
I guess you can make SecondaryForm take in the parent form in the constructor, and the add an event handler in the constructor.
private void start_form_button_Click(object sender, EventArgs e)
{
SecondaryForm new_form = new SecondaryForm(this);
new_form.Show();
}
In SecondaryForm.cs:
public SecondaryForm(ISomeView parentView)
{
parentView.SomeEvent += .....
}

Categories