I have windows form which is calling another class's method and need to be passed as parameter.
public partial class Form1 : Form
{
private myClass _myClass;
public Form1()
{
InitializeComponent();
_myClass = new myClass(//pass this instance - Form1 - as parameter)
}
}
But I don't know how to pass Form1 instance as parameter? I need to do this, because this other class is creating system tray icon and menu strip and is able to close the parent form.
You'd just do:
_myClass = new myClass(this);
And then change the constructor in myClass:
public class myClass
{
private Form1 theForm;
public myClass(Form1 theForm)
{
this.theForm = theForm;
}
...
}
Now you can access the form from within the class. I think I'd avoid doing this though. Try to leave the form in charge of calling the class and determining when it should close itself.
Having the class hold a reference back to the form that instantiated it, and closing it from within the class seems like it could lead to confusion and maintainability issues down the road.
Simply declare a parameter of type Form in the other's class constructor:
public class myClass
{
private Form otherForm;
public myClass(Form form)
{
otherForm = form;
}
}
and call it from within Form1:
_myClass = new myClass(this);
I can't figure out what you want to achieve. but if you just want to pass this form than you can use this.
_myClass = new myClass(this);
Sure you can:
_myClass = new myClass(this);
Unless I'm missing something, this ought to be fairly straightforward:
public Form1(myClass instance)
{
InitializeComponent();
_myClass = instance;
}
Related
I need some help with C#.
Let's say I have 3 classes. MainMenu, Form1 and Data.
I have created an instance of Data (referenced as StoreData) in MainMenu.
public partial class MainMenu : Form
{
public Data StoreData = new Data();
}
I want to be able to access this instance of StoreData in Form1. How do I reference it or import it?
You can either
Make StoreData static 🤮 in a static class MyAWesomeStatic and call MyAWesomeStatic.StoreData or even in MainMenu class iteself.
Pass a reference of StoreData to Form1 either via the constructor or a property when you create it.
or pass a reference of MainMenu to form1 and call mainMenu.StoreData when needed.
However, another option might be to use Dependency Injection (DI) and Loosely Couple all this. Have a Singleton instance and pass the in-memory Data Store as some sort of Service (which is what the cool kids might do).
Update
Sorry, still at the beginning stages of learning C#. What does it mean
to make a class static?
Given your current level of knowledge and all-things-being-equal, i think the easiest approach might be just pass in a reference
public class Form1
{
public Data StoreData { get; set; }
}
...
var form = new Form1();
form.StoreData = StoreData;
form.Show();
If you want to reference one class within another class (and don't want to make anything static), composition is one way to go.
You want to reference field of MainForm in Form1, so you want to reference MainForm itself. Thus, you need to create field in Form1 of MainForm type:
public class Form1 : Form
{
...
public MainForm mf { get; set; }
...
}
Now, you can access StordeData with mf.StordeData within Form1.
You could make StoreData static in a static class, something like this:
public static class Form1
{
public static Data StoreData { get; set; }
}
Suppose your StoreData class have one property
public class StoreData
{
public int MyProperty { get; set; }
}
Add static property to your mainform.cs and assign value to MyProperty = 1
public partial class MainMenu : Form
{
public static StoreData Data { get; set; } //static property
private void MainMenu_Load(object sender, EventArgs e)
{
Data = new StoreData { MyProperty = 1 };
}
}
And access your StoreData property inside Form1.cs like
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
var id = MainMenu.Data.MyProperty;
}
}
Try once may it help you
Result:
I've tried the bellow code which is working but it keeps opening multiple forms every time i call calltest() method. How can i call test() method without opening it's form? Should i move all my methods to another class file? Thanks
namespace test1
{
public partial class MainForm : Form
{
public void test()
{
//code
}
...
}
}
namespace test1
{
public partial class SecondForm : Form
{
private void calltest()
{
MainForm form1 = new MainForm();
form1.test();
}
...
}
}
You might want to reconsider your design. However, here is a direct answer to your question:
The issue you are having is because each time in the calltest method, you are creating a new instance of MainForm.
Instead, you should inject the original instance of MainForm and store it inside an instance variable inside SecondForm like this:
public partial class SecondForm : Form
{
MainForm form1 = null;
public SecondForm(MainForm main_form)
{
form1 = main_form;
}
private void calltest()
{
form1.test();
}
...
}
Now when you create your instance of SecondForm, make sure that you inject the original instance of MainForm with something like this:
SecondForm second_form = new SecondForm(main_form); //If you are creating this from MainForm, then simply pass `this` as the construction parameter
For example after creating a new Windows Form project I have my class called Form1.cs and from that form I can simply start typing the name of a form control and it will auto populate the form control variable names and I am able to use them in the class. However I have other classes that need to be able to access these form control variables as well, but they are not accessible.
Make them public if they are going to be used in another assembly, or internal if they are going to be used in the same project. Making them static means you don't have to pass your Form1 into the other classes.
Example... Say your Form1 has a string that contains the text you display in the title bar. Making it internal static, like this:
internal static readonly string MsgBox_Title = " Best Application Evar!";
lets you access it from other classes like this:
Form1.MsgBox_Title
It doesn't have to be readonly; that's just an example I pulled from an old app...
If you don't want static variables, you'll have to pass in an instance of Form1.
public class SomeClass
{
private Form1 m_Form1;
public SomeClass(Form1 form1)
{
m_Form1 = form1;
}
private void someMethod()
{
string localValue = m_Form1.SomeMemberStringVariable;
}
}
It's a very contrived example, but hopefully you get the idea.
If you want to call the Refresh method from a class instantiated from Form1, you could use an event in the child class to notify Form1.
Example:
This Form1 has a button that I use to show a secondary form.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnShowPopup_Click(object sender, EventArgs e)
{
PopupForm f = new PopupForm();
f.CallRefreshHandler += PopupForm_CallRefreshHandler;
f.ShowDialog();
}
private void PopupForm_CallRefreshHandler(object sender, EventArgs e)
{
Refresh();
}
}
The secondary form, "PopupForm", has a button that I use to raise an event that the Form1 is subscribed to, and lets Form1 know to call Refresh.
public partial class PopupForm : Form
{
public event EventHandler CallRefreshHandler;
public PopupForm()
{
InitializeComponent();
}
private void btnRaiseEvent_Click(object sender, EventArgs e)
{
EventHandler handler = CallRefreshHandler;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
Hope this helps.
Create an object of that class & start using those variables like this
Form1 fm = new Form1();
string abc = fm.VAR;
Define a public property in your form.
public string MyProp { get; set; }
Form1 frm = new Form1();
frm.MyProp = "Value";
Or define the property as static to avoid having to instantiate Form1:
public static string MyProp { get; set; }
Form1.MyProp = "Value";
I ran into this issue recently. I was keeping some methods in a separate class. Maybe not a good design decision in my case, I'm not sure yet. And these methods sometimes needed to communicate with controls in the main Form1. For example, to write to textBox1.
Turns out easy enough. Just write your method signature to include a TextBox instance. For example you pass textBox1 in and inside the method you refer to it as tb. Then when you call that method (even though it is in another class) you set the tb.Text property to whatever you like and it will show on textBox1.
This makes sense when you consider that control is just a special kind of object, graphically represented in the Form. When you pass it as an argument to a method in another class or the same class, you are actually passing the reference. So writing text to it in the method call will write text to the original control.
im writing an application in visual studio and im trying to access a rich text box from an other class. This doesnt seem to work for me. Also how to i call a function from an other class?
My code:
namespace Test{
public partial class Form1 : Form
{
public Form1()
{
// I want from this place to access the MyClass.test("hello");
}
}
}
namespace Test{
class MyClass
{
public void test (string text)
{
// here i want to do richtextbox1.clear(); but the textbox is not available
}
}
}
can be done in many ways. My favorite would be to declare the object of the "MyClass" class within "Form1" by passing the "this" pointer as an argument. Thus, the object of the "MyClass" class will have access to all the members and public functions "Form1". Included RichTextBox1.
namespace Test{
public partial class Form1 : Form
{
MyClass MyClassObject;
public Form1()
{
InitializeComponent();
MyClassObject=new MyClass(this);
MyClassObject.test("hello");
}
}
}
namespace Test{
class MyClass
{
Form1 parent;
public MyClass(Form1 parentForm)
{
parent=parentForm;
}
public void test (string text)
{
parent.richtextbox1.clear();
}
}
}
You don't want to do this. You can for example do it like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var myClass = new MyClass(this.richtextbox1);
myClass.SetTextBoxText("hello");
}
}
class MyClass
{
RichTextBox _textBox;
public MyClass(RichTextBox textBox)
{
_textBox = textBox;
}
public void SetTextBoxText(string text)
{
_textBox.Clear();
_textBox.Text = text;
}
}
This uses constructor injection to pass the textbox to operate on to the contstructor. In Form1's constructor the MyClass is instantiated with a reference to the textbox, which is initialized in InitializeComponent(). Then when you call SetTextBoxText, the class clears the associated textbox's text and then sets it to the passed text.
This is more specific than the commonly suggested method: just pass the entire Form1 instance to MyClass's constructor after making the textbox public, but that way you cannot reuse MyClass for other forms.
But as you see, it's pretty pointless to do. You can let Form1 contain this.richttextbox1.Text = "hello"; directly.
It is not quite clear from your question, but I'm supposing your richtextbox1 is located at Form1.
By default all UI elements of form has private acess modifier - that's why you can't access your richtextbox1 from outer class.
You can change it's access mmodifier to public - but I strongly encourage you not to do it.
Instead write some method in Form1 class like
public void ClearRichTextBox()
{
richtextbox1.Clear();
}
and use it.
I have a class in the same namespace as my form. Is it possible for me to access methods/properties of my form controls from my class? How can I accomplish this?
You need to make your controls public, however I wouldn't do that. I'd rather expose just what I need from my controls. So say if I needed access to the text in a text box:
public class Form1 : Form
{
public string TextBoxText
{
get{return this.textBox1.Text;}
set{this.textBox1.Text = value;}
}
}
One way is to pass the form into the class like so:
class MyClass
{
public void ProcessForm(Form myForm)
{
myForm.....; // You can access it here
}
}
and expose the Controls that you want so that you can access them but really you should pass only what you need to the class, instead of the whole form itself
If you pass a reference of your form to your class you should be able to access methods and properties of your form from your class:
public class MyClass
{
private Form form;
public void GiveForm(Form form)
{
this.form = form;
}
}
You need to generate stubs.
For that
In your custom class write a constructor
public YourClass(Main main)
{
// TODO: Complete member initialization
this.main = main;
}
then in main class/form class, initialize your class
YourClass yesMyClass = YourClass(this);
If your want to access form components on your custom class then,
this.main.label1.Text="I done that smartly'