I'm trying to call a function in a main form from another form... Already got to call a simple function, by declaring it public static in main form, yet I can't call the needed one.
The function to call:
public static void spotcall()
{
string dial = Registry.CurrentUser.OpenSubKey("SOFTWARE").OpenSubKey("INTERCOMCS").GetValue("DIAL").ToString();
MainForm.txtSendKeys.Text = dial;// Here it asks me for a reference to an object.
foreach (char c in txtSendKeys.Text)
{
sideapp.Keyboard.SendKey(c.ToString(), checkBoxPrivate.Checked);
}
txtSendKeys.Clear();
}
The procedure I use to call it from a child form:
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Hoho";
MainForm.spotcall();
}
I completely admit that I lack some theory about C#, but as it often happens, I just have to do it for my work, so I expect to get help if by chance I don't get to the solution by myself. Thank you :)
You cannot reference instances of controls on your MainForm in a static method. Like the compiler is telling you, you need an instance of the form in order to update things like TextBoxes. Without an instance, where would the values you are trying to update go?
I'm not sure exactly how the child form is being created, but one way you could call methods on your MainForm would be to provide a reference to your MainForm instance directly to the child form. This could be through the constructor or some public property.
For example
public class ChildForm : Form {
public MainForm MyParent { get; set; }
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Hoho";
// Now your child can access the instance of MainForm directly
this.MyParent.spotcall();
}
}
Assuming you are creating ChildForm inside of MainForm the code to give the child a reference is pretty simple:
var childForm = new ChildForm();
childForm.MyParent = this; // this is a `MainForm` in this case
childForm.Show();
You would also need to make spotcall an instance method and not a static method, and remove the static reference to MainForm in your code:
public void spotcall()
{
string dial = Registry.CurrentUser.OpenSubKey("SOFTWARE").OpenSubKey("INTERCOMCS").GetValue("DIAL").ToString();
// Now it no longer asks you for a reference, you have one!
txtSendKeys.Text = dial;
foreach (char c in txtSendKeys.Text)
{
sideapp.Keyboard.SendKey(c.ToString(), checkBoxPrivate.Checked);
}
txtSendKeys.Clear();
}
I think the correct way to do this is to use delegates. This way your form (window) does not have to know anything about the parent form (the form can be opened from different parent forms).
Let's say we want to call a function in the parent form when the child form is closed (not showing the form as modal).
At the top of your child form create a delegate:
public delegate void CloseEvent();
public CloseEvent WindowClosed;
Create the form closing event and have it call your delegate:
private void child_FormClosing(object sender, FormClosingEventArgs e)
{
WindowClosed();
}
A button in the parent form can show the child form and set the callback:
private ChildForm childform = null;
private void buttonShowChildForm_Click(object sender, EventArgs e)
{
if (childform == null)
{
childform = new ChildForm();
childform.WindowClosed += childClosed;
childform.Show();
} else
{
childform.BringToFront();
}
}
private void childClosed()
{
childform = null;
}
In this example we use a button to open a new form that does not block the parent form. If the user tries to open the form a second time, we just bring the existing form to the front to show it to the user. When the form is closed we set the object to null so that next time we click the button a new form is opened because the old was disposed when closed.
Best regards
Hans Milling...
You can not access non-static members in static context, which means you have to made txtSendKeys static, or make your function non-static.
If you create a static function, you may not reference global variables inside the function that aren't static as well.
So in order for spotcall to be static, you have to remove the reference to the txtSendKeys (I'm assuming this is a text box that you have created elsewhere in the form) or txtSendKeys must be declared within the static function.
Additional:
You obtained the value for txtSendKeys.Text in the previous line, via variable dial. Instead of referencing txtSendKeys.Text at all, I imagine you could simply use the variable dial to complete the function and leave the function static (you clear it at the end anyway).
public static void spotcall()
{
string dial = Registry.CurrentUser.OpenSubKey("SOFTWARE").OpenSubKey("INTERCOMCS").GetValue("DIAL").ToString();
foreach (char c in dial)
{
sideapp.Keyboard.SendKey(c.ToString(), checkBoxPrivate.Checked);
}
}
Although, that wouldn't overcome the same issue you would likely run into with checkBoxPrivate.Checked.
You could change it to take a boolean argument.
public static void spotcall(Boolean PrivateChecked)
{
string dial = Registry.CurrentUser.OpenSubKey("SOFTWARE").OpenSubKey("INTERCOMCS").GetValue("DIAL").ToString();
foreach (char c in dial)
{
sideapp.Keyboard.SendKey(c.ToString(), PrivateChecked);
}
}
You can put the shared code in a third class that's visible to both forms. So, for example:
public class static HelperFunctions
{
public static void spotcall()
{
. . .
}
}
Then replace
MainForm.spotcall()
with
HelperFunctions.spotcall()
The MainForm is just a class. It has the structure of the class. But the only data you can get from it is static data.
But an instance of that class appears when you do: MainForm MyFormInstance = new MainForm();
The MainForm can be used only to access static members (methods, properties...).
When you want to get the txtSendKeys, you must get it from an instance (object reference). That's because the textbox is not static, so it only exists in instances of the form.
So, you should do the following:
Make spotcall NOT static.
Put in child form a variable MainForm MyParentMainForm;
When you call the child, set that MyParentMainForm with the instance of the mainform. If it's being called from the main form, you can get the instance with the this keyword.
Inside child form, call MyParentMainForm.spotcall
PS: I'm not sure if there's something like a real child form or if you just call new forms from another. If there's really a child form, you can get the Parent property to access the instance of the main form.
This is sort of a "design pattern" issue, which I'll elaborate on, but I can try to explain the most direct way to solve this if you don't expect this program to change very much. "Static" things only exist once - once in the entire application. When a variable or function is static, it's much easier to access from anywhere in the program; but you can't access an object's associated data, because you're not pointing to a particular instance of that object (ie, you have seven MainForms. Which one are you calling this function on?) Since standard WinForm design expects you could have seven copies of MainForm displaying, all variables associated are going to be instance variables, or non-static. However, if you expect never to have a second MainForm, then you can take the "singleton" approach, and have an easy way of accessing your one instance.
partial class MainForm {
// only including the code that I'm adding; I'm sure there's a lot of stuff in your form.
public static MainForm Instance { public get; private set; }
protected void onInitialize() { // You need to hook this part up yourself.
Instance = this;
}
}
partial class SubForm {
protected void onImportantButton() {
MainForm.Instance.doImportantThing()
}
}
Putting too much active data-changing logic in form classes is a pretty common issue with many beginners' code. That's not a horrible thing - you wouldn't want to be making 5 controlling classes just for a simple thing you're trying. As code gets more complex, you start to find some things would make more sense to move to a "sublevel" of classes that don't interact with the user (so, some day, if this is being re-coded as a server program, you could throw away the form classes, and just use the logic classes - theoretically speaking). It also takes some time for many programmers to understand the whole concept of object "instances", and the "context" that a function is called in.
Related
I have a windows form app with 2 forms, and I need to press a button in form one to go to form 2(this is done already) then form 2 will be able to create an object using the add customer method to add to the system. My question is:
1)if I create an Object in Form 2, how could other forms(form3,form4 etc.) have access to this object? As far as I have learned, I can only call the method through an object.
2)if I created an object in Form1, and other forms inherited from form 1, will this object still work in other forms?
3)Objects can be inhereited or not? is this a good practice in real world?
4) How to allow different forms using one object different method?
A static field or property as suggested in zdimension's answer is possible, of course, but it shouldn't be your first option. There are lots of ways to pass data between forms, and it depends on your application which one is best. For example, one way of doing it is:
class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public AirlineCoordinator Coordinator {get; set;}
...
}
class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public AirlineCoordinator Coordinator {get; set;}
private void Form1_Load(object sender, EventArgs e)
{
this.Coordinator = new AirlineCoordinator(...);
...
}
...
private void ShowForm2Button_Click(object sender, EventArgs e)
{
using(var form2 = new Form2())
{
form2.Coordinator = this.Coordinator;
form2.ShowDialog(this);
}
}
}
In this hypothetical example, Form1 has a button ShowForm2Button; clicking on this button shows Form2 using the same AirlineCoordinator as is used by Form1.
The usual way to make something available to "everyone" is to use a static field, like this:
public class GlobalStuff
{
public static MyType SomeVariable;
}
Here, the GlobalStuff obviously only ever contains global things, so you could consider making it static too to indicate it will never be instanciated.
Here's what MSDN say about it:
Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods. It is useful to organize the methods inside the class in a meaningful way, such as the methods of the Math class in the System namespace.
I have a problem. I am trying to access a panel in a user control.When I access it in a form it works. Earlier on I did this.
I accessed a panel in a form from a user control and it worked. Below is the code I used:
Form1 form = Application.OpenForms.OfType<Form1>().FirstOrDefault();
form.Panel1.Controls.Clear();
ManageControl user = new ManageControl();
form.Panel1.Controls.Add(user);
But when I try to use the very same concept in a user control it does not work.
It throws a null error: Object reference not set to an instance of an object.
Below is the code:
//this is in ManageControl.cs
public Panel Panel2
{
get { return panelmanage; }
}
//this is in another userControl.Trying to access panelImage
ManageControl form = Application.OpenForms.OfType<ManageControl>().FirstOrDefault();
form.Panel2.Controls.Clear();//it throws the error here
ReportControl user = new ReportControl();
form.Panel2.Controls.Add(user);
What am I doing wrong because I am using the same concept?
EDIT:
This is my ManageControl.cs
public partial class ManageControl : UserControl
{
public ManageControl()
{
InitializeComponent();
}
public Panel Panel2
{
get { return panelmanage; }
}
This is how I try to access it in BookingListControl
public partial class BookingListControl : UserControl
{
ManageControl form = Application.OpenForms.OfType<ManageControl>().FirstOrDefault();
public BookingListControl()
{
InitializeComponent();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
ManageControl form = Application.OpenForms.OfType<ManageControl>().FirstOrDefault();
ReportControl user = new ReportControl();
form.Panel2.Controls.Add(user);
}
ManageControl is a UserControl not a Form. Thus, when you look for open forms of type ManageControl, you get nothing (no surprises here). Then, we you call FirstOrDefault it returns null (since there were no matching elements in the empty collection), and your next line blows up.
This approach is doomed from the start, because even if you had a whole bunch of forms overlaying each other and could make it work (bad idea), it would break once you had two ManageControl objects and needed to access the second.
Instead, first ask yourself, "Why do my UserControl objects need to access each other?". This is an important question, because in general UserControls are independent. They likely have methods to give data back to their parent, but thats it. They certainly don't interact with other UserControls.
If you decide that you really need this dependency, then I would pass the parent Form object to both UserControls and have a public property on the Form that allows them to see the other UserControl. From here you can access it normally (without needing any OpenForms nonsense). Honestly though, this is a massive code smell and it sounds like the whole design should be looked at to see where you have dependencies that could be removed.
To do this you need to expose the ManageControl on the form:
public class ParentForm : Form
{
public ManageControl Manager { get { return manageControlInstance; } }
...
}
Then access it in your child control. The easiest way would be through the Parent property, but you could pass it on the constructor or an Init function as well.
public class ChildControl : UserControl
{
private void SomeFunction()
{
(Parent as ParentForm).Manager.Panel2.Controls.Add(new ReportControl());
}
}
The code's pretty ugly, and I wouldn't recommend it (its also not safe if you put the ChildControl into anything other than a ParentForm). That being said it would work.
Assuming that the NullReferenceException occurred based on accessing the "Panel2" property, your issue is that "panelmanage" is null. Is the code that finds and populates "form.Panel2" in a form or control constructor? If so, try restructuring it to run after ManageControl is fully initialized - perhaps by putting it into a Loaded event.
I've a problem with my C# Code. At the moment I try to program a Windows Forms Application with more than one Window.
Now my problem:
At the first window I've a combobox with some values. When I click on a button, the second window opens and there it should be possible to add a value to this combobox on the first form.
The problem is that in the first window I´ve a LinkedList where my values are in.
Like this:
public LinkedList<String> sample = new LinkedList<String>();
hase.AddFirst("test");
combobox.Items.AddRange(sample.ToArray());
Now, in the second window the LinkedList isn't available, even if I make it public.
What is the best way to solve this problem?
Hope you understand my problem...
Harald
Without knowing exactly how to are trying to access the LinkedList, it's hard to say why it isn't working for you.
Let's go over what you have. You have a LinkedList, which is an instance variable on a form. Since this LinkedList is an instance variable, it is associated with the instance of the form.
This example below, will not work because it tries to access it statically:
public class MyForm : Form
{
public LinkedList<string> _list = new LinkedList<string>();
}
public class MySecondForm : Form
{
public void Window_Loaded(object sender, EventArgs e)
{
MyForm._list.AddFirst("This doesn't work");
//WRONG! list is an instance variable we are trying to access statically.
}
}
So, we can see this does not work. We have a few options to get this working. First off, one very bad solution would be to actually make list static. Don't use this option. It's opens the door for concurrency problems, possibly leaking strong references, etc. Generally, using statics (like a singleton) I would discourage for passing data around for these reasons. The Singleton Pattern has a time and a place, but I don't think this is it since it can so easily be avoided.
OK, since we got the bad solution out of the way, let's look at a few possible good ones.
Set the list on MySecondForm. You have a few options for this. The constructor, a property, or a method. For example:
public class MyForm : Form
{
private LinkedList<string> _list = new LinkedList<string>();
public void Button1_Click(object sender, EventArgs e)
{
var secondForm = new MySecondForm();
secondForm.SetList(_list);
secondForm.ShowDialog();
MessageBox.Show(_list.First.Value);
}
}
public class MySecondForm : Form
{
private LinkedList<string> _list;
public void Window_Loaded(object sender, EventArgs e)
{
this._list.AddFirst("This will work");
}
public void SetList(LinkedList<string> list)
{
_list = list;
}
}
This is one possible solution. The constructor is another possible solution as Billy suggested.
Because LinkedList is a reference type, any changes you make to it on the instance of MySecondForm will be reflected on the linked list of MyForm.
You can always pass it to the second window. As vcsjones points out below, you should only need to add the ref keyword if you are re-assigning the list. You will need a constructor that takes a linked list as a variable.
SecondWindow secondWindow = new SecondWindow(sample);
Another way would be create a class using the singleton pattern and you can place the linked list in there. You would then have access to it from both windows if it was in a common location.
How do i show a from that have been hidden using
this.Hide();
I have tried
MainMenuForm.Show();
and this just says i need an object ref. I then tried:
MainMenuForm frmMainMenu = new MainMenuForm();
frmMainMenu.Show();
Which seems to show the appropriate form. But when you exit the app, it is still held in memory because it hasn't shown the form that was hidden, instead it has shown a new version of the form. In effect having 2 instances of the form (one hidden, one visible).
Just to clarify, the MainMenuForm is the startup form. When (for example) Option 1 is clicked, the MainMenuForm then hides itself while opening up the Option 1 form. What i would like to know is how to i make the Option 1 form that the MainMenuForm opens "unhide" the MainMenuForm and then close itself.
What's the correct procedure here?
Thanks in advance.
When you do the following:
MainMenuForm frmMainMenu = new MainMenuForm();
frmMainMenu.Show();
You are creating and showing a new instance of the MainMenuForm.
In order to show and hide an instance of the MainMenuForm you'll need to hold a reference to it. I.e. when I do compact framework apps, I have a static classes using the singleton pattern to ensure I only ever have one instance of a form at run time:
public class FormProvider
{
public static MainMenuForm MainMenu
{
get
{
if (_mainMenu == null)
{
_mainMenu = new MainMenuForm();
}
return _mainMenu;
}
}
private static MainMenuForm _mainMenu;
}
Now you can just use FormProvider.MainMenu.Show() to show the form and FormProvider.MainMenu.Hide() to hide the form.
The Singleton Pattern (thanks to Lazarus for the link) is a good way of managing forms in WinForms applications because it means you only create the form instance once. The first time the form is accessed through its respective property, the form is instantiated and stored in a private variable.
For example, the first time you use FormProvider.MainMenu, the private variable _mainMenu is instantiated. Any subsequent times you call FormProvider.MainMenu, _mainMenu is returned straight away without being instantiated again.
However, you don't have to store all your form classes in a static instance. You can just have the form as a property on the form that's controlling the MainMenu.
public partial class YourMainForm : Form
{
private MainMenuForm _mainMenu = new MainMenuForm();
protected void ShowForm()
{
_mainMenu.Show();
}
protected void HideForm()
{
_mainMenu.Hide();
}
}
UPDATE:
Just read that MainMenuForm is your startup form. Implement a class similar to my singleton example above, and then change your code to the following in the Program.cs file of your application:
Application.Run(FormProvider.MainMenu);
You can then access the MainMenuForm from anywhere in your application through the FormProvider class.
The simplest and easiest way is to use LINQ and look into the Application.OpenForms property. I'm assuming you have only 1 instance of the form (hopefully!), otherwise make sure to have to have some public property on the hidden form to be able to differentiate it.
The following code will un-hide the form for you:
var formToShow = Application.OpenForms.Cast<Form>()
.FirstOrDefault(c => c is MainMenuForm);
if (formToShow != null)
{
formToShow.Show();
}
You need to keep a reference to the first form when it's created and then the code that holds that reference can call Show on it.
If you don't open that form from somewhere but it's set as the startup form, then you either need to change it so that you have a Main method that opens that form or you can have that form store a reference to itself somewhere that can be accessed from other places.
For example, an quick and ugly way would be to, add a public static property to your mainform and then when you hide the form it also writes this to that property which can then be retrieved when needed by other parts of the code.
Practically This works for me....
public class MainWindow : Form
{
Form _mainMenuForm = new MainMenuForm();
}
calling it through a button click event.
private void buttonclick()
{
if (_mainMenuForm.Visible)
{
_mainMenuForm.Visible = false;
}
else
{
_mainMenuForm.Visible = true;
}
}
Store a reference to the form and call .Hide() and .Show() on that.
For example:
public class MainWindow : Form
{
private Form _mainMenuForm = new MainMenuForm();
public void btnShowMenuForm_Click(...)
{
_mainMenuForm.Show();
}
public void btnHideMenuForm_Click(...)
{
_mainMenuForm.Hide();
}
//etc
}
This example assumes you have a form which is launching the MainMenuForm.
Call the referenced form.
Like:
Calling parent
----------
public MyForm f {get;set;}
void DoStuff()
{
f = new MyForm();
f.Show();
}
MyForm
----------
void DoOtherStuff()
{
this.hide();
}
Parent
----------
void UnHideForm()
{
f.show();
}
Another simpler method to achieve this is to loop through the open forms to see which are still running and open it...
foreach (Form oForm in Application.OpenForms)
{
if (oForm is MainMenuForm)
{
oForm.Show();
break;
}
}
I have a form that has a public property
public bool cancelSearch = false;
I also have a class which is sitting in my bll (business logic layer), in this class I have a method, and in this method I have a loop. I would like to know how can I get the method to recognise the form (this custom class and form1 are in the same namespace).
I have tried just Form1. but the intellisense doesn't recognise the property.
Also I tried to instantialize the form using Form f1 = winSearch.Form1.ActiveForm; but this too did not help
Any ideas?
When you are calling the business logic that needs to know the information pass a reference of the form to the method.
Something like.
public class MyBLClass
{
public void DoSomething(Form1 theForm)
{
//You can use theForm.cancelSearch to get the value
}
}
then when calling it from a Form1 instance
MyBlClass myClassInstance = new MyBlClass;
myClassInstance.DoSomething(this);
HOWEVER
Really you shouldn't do this as it tightly couples the data, just make a property on your BL class that accepts the parameter and use it that way.
I think you should look at how to stop a workerthread.
I have a strong feeling that you have a Button.Click event handler that runs your business logic and another Button.Click that sets your cancelSearch variable. This won't work. The GUI thread which would run your business logic, won't see the other button being clicked. If I'm right you should very much use a worker thread.
Your question is really not clear. You might want to edit it.
Advice
The form shouldn't pass to your business logic layer...
Solutions to your problem
BUT if you really want to (BUT it's really not something to do), you need to pass the reference. You can do it by passing the reference in the constructor of your class, or by a property.
Method with Constructor
public class YourClass
{
private Form1 youFormRef;
public YourClass(Form1 youFormRef)
{
this.youFormRef = youFormRef;
}
public void ExecuteWithCancel()
{
//You while loop here
//this.youFormRef.cancelSearch...
}
}
Method with Property
public class YourClass
{
private Form1 youFormRef;
public int FormRef
{
set
{
this.youFormRef = value;
}
get
{
return this.youFormRef;
}
}
public void ExecuteWithCancel()
{
//You while loop here
//this.youFormRef.cancelSearch
}
}
As the other (very quick) responses indicate, you need to have an instance variable in order to get your intellisence to show you what you need.
Your app by default does not have a reference to the main form instance, if you look at your program.cs file you will see that the form is constructed like so...
Application.Run(new Form1());
so you have a couple options, you could create a global var (yuck) and edit your program.cs file to use it..
Form1 myForm = new Form1();
Application.Run(myForm);
Pass a reference to the business object from your running form like some others have suggested
myBusinessObj.DoThisThing(this);
or find your form in the Application.OpenForms collection and use it.