I am trying to execute code in a UserControl when an even from the main form is raised.
The Form code:
public partial class mainForm : Form {
...
public event EventHandler listBoxIndexChanged;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
listBoxIndexChanged?.Invoke(sender, e);
}
}
Important to mention here is that the actual form's Name is also mainForm, just like the classname.
The UserControl code:
public partial class userControl1 : UserControl {
public userControl1() {
InitializeComponent();
mainForm.listBoxIndexChanged += mainForm_listBox1_IndexChanged;
}
private void mainForm_listBox1_IndexChanged(object sender, EventArgs e) {
// my code
}
}
This code is throwing the error An object reference is required for the non-static field, method, or property 'mainForm.listBoxIndexChanged'. I'm sure it's something obvious, but what could I be doing wrong?
WinForms .NET Framework 4.8, VS 2019.
The way this runs is that MainForm is created first and then creates an instance of your UserControl inside the MainForm. So, MainForm knows about UserControl but UserControl does not know about MainForm. So when you tell UserControl to use MainForm it doesn't know what MainForm is (no instance). Instead you'll want the MainForm to trigger a method inside the UserControl and pass it the needed information.
In your user control create a method that the MainForm can call:
public class UserControl1
{
public void doSomethingWhenSelectedIndexChanges(int selectedIndex){
// do stuff inside user control...
}
}
Then in your MainForm call the UserControl method.
public class MainForm
{
private void ListBox1_SelectedIndexChanged(object sender, eventargs e)
{
UserControl1.doSomethingWhenSelectedIndexChanges(ListBox1.SelectedIndex);
}
}
This way the MainForm is telling the UserControl that the ListBox selected index has changed and is passing the selected index to the UserControl.
Related
I have 2 forms, let's call them form1 and form2. Inside form1 i have created a method that connects to an access database, and also inserts the values from the database into a combobox. My question is : how do i call my method which is inside my form1, for a combobox inside form2? The error that i get says The name "MyComboBoxName" does not exist in the current context.
I have tried to use inheritence between my 2 classes, but then i get 2 of the same comboboxes.
The easiest solution is to define your method statically in the first form:
public partial class Form1 : Form
{
public static void CustomMethod()
{
//Your codes
}
public Form1()
{
InitializeComponent();
}
}
Then call it from the second form:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Form1.CustomMethod();
}
}
I am creating Windows form application and its main form contains a panel. Different user controls are being loaded on that panel on button click.
namespace LearnCSharp
{
public partial class MainForm : Form
{
private void configButton_Click(object sender, EventArgs e)
{
var uControllerDashboard = new Controllers.Dashboard();
panel.Controls.Add(uControllerDashboard);
updateNotification("active");
}
private void updateNotification(string state)
{
switch (state)
{
case "active" :
//Do something here
break;
}
}
}
}
when click config button it loads Dashboard user controller into Panel there is a another apply button in Dashboard userControl. When I click that button I need to call updatNotification method in MainForm Class.
namespace LearnCSharp.Controllers
{
public partial class Dashboard : UserControl
{
private void btnApply_Click(object sender, EventArgs e)
{
// Need to call updateNotification method here.
}
}
}
how can I achieve my requirement. I appreciate any help. Thanks.
Use events for that.
Instead of calling the MainForm inside the UserControl, create an event in the UserControl and have the MainForm subscribe that event. Inside the UserControl you just need to trigger the event.
There are many examples on web about this. Just take a look at this:
How do I make an Event in the Usercontrol and Have it Handeled in the Main Form?
How do i raise an event in a usercontrol and catch it in mainpage?
Hope this helps.
I have around 20 forms in my Project of C#. I have created a method in a Class. I want all the 20 forms to call that method in their Load event. I can put the Call statement in the Load Event of each form one by one. However, in future the forms may increase. Also, it may be possible that some form gets missed to write that Call statement in its Load event mistakenly.
Is their any logic, that the specific method can handle the load events of all the forms of the Project? We can get the list of all the forms of the project by using System.Reflection. So, is it possible to attach the load events of all these forms to the same specific method of the class?
You can create your custom form and override Onload (or any event)
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace test
{
public class MyForm : Form
{
protected override void OnLoad(EventArgs e)
{
MessageBox.Show("test"); //call your method(s)
base.OnLoad(e);
}
}
}
and your new form
namespace CustomFormProject
{
public partial class Form1 : MyForm
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//MessageBox will be shown automatically from your base (MyForm) class
//other codes
}
}
}
You can do something like this:
public partial class Form2 : MainForm
public partial class Form3 : MainForm
...
...
...
public partial class Form19 : MainForm
public partial class Form20 : MainForm
Inherit the MainForm in your other Forms and call the method in their Form_Load event.
The MainForm is the class in which you've created the method, further which you want to access it in the other forms.
Suppose, the example below is the Method in your MainForm.
public partial class MainForm : Form
{
public Form1()
{
InitializeComponent();
}
public void Msg()
{
MessageBox.Show("Hello");
}
}
Call the method Msg() on the Form2_Load event by first inheriting from the MainForm class:
public partial class Form2 : MainForm
^^^^^^^^
Now, call this method:
private void Form2_Load(object sender, EventArgs e)
{
Msg();
}
Similarly, you do the same thing with the rest of your Forms.
I have a main form with 3 User Controls attached to it. How can I have events inside a specific User Control reach out and modify the UI of the other two User Controls without creating spaghetti code?
Main Form (Form1.cs)
public partial class Form1 : Form
{
private UserControl1 userControl11;
private UserControl2 userControl21;
private UserControl3 userControl31;
public Form1()
{
InitializeComponent();
}
}
UserControl1.cs
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Change buttons around and fill in some data on user control 2 and 3
}
private void button2_Click(object sender, EventArgs e)
{
// Remove certain elements from control2 and 3
}
// .. So forth
}
I will have many events that do many different things on the other two user controls. I am creating a basic interface that's similar to Visual Studio where I can open projects, close them, add files, etc. These actions on one form should load up different windows and such in the other controls. What's the best method to achieve this? Creating custom events and parsing each event in the main form? Or accessing each user control directly from the first one? Or...?
The general pattern for events is:
public class MyClass{
public static EventHanlder<ofSomeType> MyEventHandler;
public void MyClass{
MyEventHandler = _MyEventHandler;
}
public void _MyEventHandler(object sender, OfSomeType args){
//do something with passed in args.
}
}
Other classes would use these eventhandlers like this...
public class myOtherClass{
public void doSomething(){
//do something here and signal the other class
var ofSomeTypeData = GetData();
MyClass.MyEventHandler(ofSomeTypeData);
}
}
Some will argue this style is too closely coupled but it works flawlessly and is a good start.
Create an event inside each UserControl. Form1 should subscribe to events on those controls.
So suppose that UserControl1 allows the user to sort the data. Then you might write this:
public Form1()
{
InitializeComponent();
// I assume UserControl1 was created by this point
userControl1.OnDataSorted = DataSorted;
}
// This will be called when the user wants to sort the data
private void DataSorted(UserControl1 sender, EventArgs e)
{
// Change buttons around and fill in some data on user control 2 and 3
}
Then you will create an event and a delegate in the UserControl.
public class UserControl1 {
public delegate void DataSortedDelegate(UserControl1 sender, EventArgs e);
public event DataSorted OnDataSorted;
private void button1_Click(object sender, EventArgs e)
{
if (OnDataSorted != null)
OnDataSorted(this, EventArgs.Empty);
// Replace EventArgs.Empty above with whatever data Form1 needs
}
This approach creates a separation of concerns between Usercontrol1 and Form1. The control does not need to actually modify the private controls inside Form1. It merely notifies Form1 that something has happened, and allows Form1 to make the changes.
I have 3 forms
FormBase which has no onload event
FormBaseDetail : FormBase ->
on this form I used the visual designer to create an on_load event
FormBoxDetail : FormBaseDetail ->
on this form I also used the visual designer to create an on load event
When FormBoxDetail is created, the onload event on FormBaseDetail is called but not the onload event on FormBoxDetail. This is never called.
What am i doing wrong ?
public partial class FormBase : Form
{
public FormBase()
{
InitializeComponent();
}
}
public partial class FormBaseDetail : FormBase
{
public FormBaseDetail()
{
InitializeComponent();
}
private void FormBaseDetail_Load(object sender, EventArgs e)
{
MessageBox.Show("FormBaseDetail");
}
}
public partial class FormBoxDetail : Test_app.FormBaseDetail
{
public FormBoxDetail()
{
InitializeComponent();
}
private void FormBoxDetail_Load(object sender, EventArgs e)
{
MessageBox.Show("why am i not getting called");
}
}
There is only two reasons why Load event can be not fired:
Event handler FormBoxDetail_Load is not attached to Load event. But you are saying its not your case.
You are not loading FormBoxDetail. Make sure you are creating instance of FormBoxDetail class. Probably you are using FormBaseDetail instead. Make sure you are using correct form class.
Here both event handlers will be fired:
var form = new FormBoxDetail();
form.Show();
First one is a FormBaseDetail_Load handler, and then goes FormBoxDetail_Load handler.
It just happen to me, when, from one executable project I instantiated (new) a class e.a. MyClasss c = new MyDll.MyClass(par), and the Form did not load.
I found that I forgot to load it:
Application.Run(c);
Regards