Fully access a control from another Form - c#

I have a main Windows Form (From1) which has a TextBox in it. I've also created another Windows Form (FindReplaceForm) which I'm going to use for implementing a form of find and replace dialog. I need to fully access all the properties and methods of my textbox in From1 from FindReplaceForm window.
Although I set the Modifiers property of my TextBox to Public, in FindReplaceForm window I can't access the text in it.

You can access the the owner form in the child using:
((Form1)Owner).textBox1.Text = "blah";
Assuming you have called your the child form using:
Form2 form = new Form2();
form.Show(this);

You need to pass a reference to the control or the form to your constructor so that you can reference the instance of the class. Add an argument of the same type as the calling form to the constructor:
private Form1 calling_form;
public FindReplaceForm (Form1 calling_form)
{
this.InitializeComponent()
this.calling_form = calling_form;
}
Then in your button call you can say:
calling_form.TextBox_value_text.SelectedText = "";

In your code, Form1 is a CLASS, not a variable. When you show your FindReplaceForm you should specify the Owner (just use this).
Now you can the Owner property on FindReplaceForm to get access to Form1.
Showing FindReplaceForm:
FindReplaceForm.Show(this);
In your button click event:
void Buttton1_Click(object sender, EventArgs e)
{
((Form1)this.Owner).TextBox_value_text.SelectedText = "";
}

Even if you set the textbox access modifier back to private, you can simply pass a reference to the textbox in the second form's constructor, thus enabling the second form to manipulate any property of the textbox:
first form:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this.textBox1);
frm.Show();
}
}
second form:
public partial class Form2 : Form
{
private TextBox _OwnerTextBox;
public Form2(TextBox ownerTextBox)
{
InitializeComponent();
_OwnerTextBox = ownerTextBox;
this.textBox1.Text = _OwnerTextBox.Text;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
_OwnerTextBox.Text = this.textBox1.Text;
}
}

In your FindReplaceForm.button1_Click function you want to control an object of class Form1. The error in your code explains that you don't call a function of an object of class Form1, but a function of class Form1 itself. The latter can only be done on static functions
You describe that you have an existing Form1 object and that your FindReplaceForm needs to change Form1 by calling functions in Form1. Probably there might be more than 1 Form1 object. Therefor your FindReplaceForm instance somehow needs to know which Form1 object it needs to control. Someone needs to tell this to your FindReplaceForm. This is usually done using the constructor of the FindReplaceForm or using a property.
public class FindReplaceForm
{
private Form1 formToControl = null;
public FindReplaceForm(Form1 formToControl)
{
this.formToControl = formToControl;
}
private void OnButton1_Click(...)
{
this.formToControl.TextBox_Value_Text.SelectedText = ...
}
Another method would be not to put the formToControl in the constructor, but as a property that you can set separately. Both methods have their advantages:
via constructor: your FindReplaceForm knows for sure there is alway a formToControl. The only place you have to check if formToControl really exists is in the constructor.
Using a default constructor with a separate FormToControl property may cause run time errors if people forget to set the FormToControl.
If you have a lot of properties, or some properties may have default values, or may be changed later, then the property method is more flexible.

Related

Use information from objects in a child form from a main form in C#

I have a C# form called Form1.cs. By pressing a button, a new Form called Form2.cs comes up and I do something in form2. I have some variables in both forms.
I want to communicate between these two forms like this.
in form1:
string s=frm2.textbox1.text;`
form2:
if(frm1.checkbox1.checked==true)
or something like these codes.
I have tried the below code:
form1:
Form2 f=new Form2(this);
f.showDialog();`
form2:
private Form1 mainForm = null;
public Form2(Form callingForm)
{
mainForm = callingForm as Form1;
InitializeComponent();
}
`
and this works. But I don't want to use pointers like "this" and call this.mainform. Is there another way to communicate between forms like function calls?
Thank you.
Here are a couple of different approaches you can take that remove the need for Form 2 to know about Form 1 and that will make Form 2 reusable:
Delegates
You can declare a delegate function on the second form, and then pass a delegate method from the first form to the second one, so the second form can call back to the first one.
That approach means your second form no longer has any direct knowledge of your first form. It also means you can reuse the second form from any form and just pass in a delegate with the correct signature. Example below:
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f=new Form2(UpdateTextBox);
f.ShowDialog();
}
private void UpdateTextBox(string newText)
{
label1.Text = newText;
}
}
Form 2:
public partial class Form2 : Form
{
public delegate void ChoiceMadeOnForm2Delegate(string choice);
private ChoiceMadeOnForm2Delegate _choiceDelegate;
public Form2(ChoiceMadeOnForm2Delegate choiceDelegate)
{
InitializeComponent();
_choiceDelegate = choiceDelegate;
}
private void saveButton_Click(object sender, EventArgs e)
{
_choiceDelegate(textBox1.Text);
Close();
}
}
In this example the delegate method just has one parameter, but if you want to pass back a series of values to Form 1 your delegate method declaration could include more parameters, or the parameter could be a class instead.
If you also want to set initial values for Form2 from Form 1 you can of course add those as constructor parameters for Form 2 and pass them in when you new up Form 2.
In your example Form 2 is shown as a dialog, but if you ever want to not show Form 2 modally you could even have a delegate on Form 1 that you pass to Form 2, so the forms can then communicate in two directions.
Use data binding and a shared class
Another approach is to use databinding, whereby you bind both forms to the same object and pass that object from Form 1 to Form 2 in its constructor when you open Form 2. When either form then changes the object those changes will then be reflected on both forms simultaneously and instantly.
To do that you need to read up on a concept called databinding and implement the INotifyPropertyChanged interface on the data class. You then bind the relevant controls on both forms to that class. Documentation on INotifyPropertyChanged can be found here
You can pass only information that Form2 needs and expose only information that Form1 needs
Form1
string valueOfForm2 = null;
using Form2 f = new Form2(this.checkbox1.Checked)
{
f.ShowDialog();
valueOfForm2 = f.ReturnValue;
}
Then use valueOfForm2 for you needs in the Form1
Form2
bool _IsForm1ValueChecked;
//By this property text will be exposed to outside of Form
public string ReturnValue { get { return this.textbox1.Text;} }
public Form2(bool isForm1ValueChecked)
{
_IsForm1ValueChecked = isForm1ValueChecked;
}
_IsForm1ValueChecked will be set in the contructor - then use it for your purpose in the Form2
I think for such stuff, I was using properties.
I prefer not access from one form the controls of the other one.
If I need information from one form, I prefer giving the access to this other form through properties.
More than that, you can define an interface that will contain all the properties/methods that you need for the communication between the forms. It will be clearer to work with an interface, you will get the information you need and won't be overloaded with other irrelevant information.
For example:
Interface IForm2
{
// your properties
string PersonName {get;} // Just an example
// your methods
}
class Form1: Form
{
private IForm2 _form2;
void Foo()
{
var pname = _form2.PersonName; // Just an example
}
}
class Form2: Form, IForm2
{
string PersonName
{
get
{
return personNameTextBox.Text;
}
}
}

How can I make my Form Control variables acessible to classes other than my Form class?

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.

Control timer in form 1 from form 2, C#

A label in form is displaying the count of timer. Now i want to stop,start and reset it using form 2. How can i do this.plz help
Forms are just classes, and the timer on Form 2 is an object inside that class.
You can change the Modifiers property of your timer to public, and then instantiate Form 2 inside Form 1, call the Show() method of Form 2, and then access your timer object which is now public.
So you have a project with 2 forms like so:
Create a button in Form 1 like so:
Place a timer object on Form 2 and change the access modifier like so:
Then put the following code under your button in form one:
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
f2.timer1.Enabled = true;
}
Now you can launch form 2 and access all of the properties on the timer on form 2 from form 1.
Does this help?
If the timer object resides in Form1, then create a public property for it:
public Timer Form1Timer { get { return timer1; } }
Then you can access this timer by having a reference to Form 1 in Form 2. You can do this by passing it in to the constructor, or having a set property on Form2. Once you have a reference to Form1, you can simply call methods on the timer:
Form1.Form1Timer.Start();
You can always create a singleton out of Form1 if you cannot pass a reference of it to Form2.
Declare your singleton:
private static Form1 _singleton
Initialize your singleton if it isnt already, and return it:
public static Form1 Singleton
{
get { _singleton ?? (_singleton = new Form1()); }
}
For best practices, make your Form1 constructor private. This of course will not work if Form1 does not have a default constructor (parameterless).
Then in Form2:
Form1.Singleton.Form1Timer.Start();
Do this
static Form1 _frmObj;
public static Form1 frmObj
{
get { return _frmObj; }
set { _frmObj = value; }
}
On Form load
private void Form1_Load(object sender, EventArgs e)
{
frmObj= this;
}
Access form and it's controls from another form
Form1.frmObj.timer1.Stop();

How can I Change something in a Form1 from a DialogBox?

Lets say I have two forms ( Form1 And Form2 ).
Form1 has a PictureBox
Form2 I has an OpenFileDialog
Form1 is the main form, so when I run the project I see Form1.
How can I change the Image in the PictureBox in Form1 from Form2?
How do I pass a value from a child back to the parent form?
Basically, expose the value that gets returned in the open file dialog with some property and let the parent form grab it.
In the Program.cs file you can set any value, either FormOptions to the form's instance .
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var frm = new Form1();
// Add the code to set the picturebox image url
Application.Run(frm);
}
In addition you can add the Constructor to Form1 and pass the parameter via constructor.
Pass one form as a parameter to a constructor of the second form or add a method that passed the reference. After you have the reference to your form you can do whatever you want with the from.
Whether to share picture box as a public member is up to you. However, I would suggest making a public method SetImage() in the first form. Second form would call form1.SetImage().
[Update]
Wait, why do you need to set image from OpenFileDialog, you just need receive fileName from the dialog, and then open the file and load into the form.
Like this:
private void button1_Click(object sender, EventArgs e)
{
using (var dialog = new OpenFileDialog())
{
var result = dialog.ShowDialog();
if (result != DialogResult.OK)
return;
pictureBox1.Image = Image.FromFile(dialog.FileName);
}
}
This is code inside of Form1.
[Update]
Here is the basic idea how to access one form from another.
public class MyForm1 : Form
{
public MyForm1()
{
InitializeComponent();
}
public void SetImage(Image image)
{
pictureBox1.Image = image;
}
private void button1_Click(object sender, EventArgs e)
{
var form2 = new Form2(this);
form2.Show();
}
}
public class MyForm2 : Form
{
private MyForm1 form1;
public MyForm2()
{
InitializeComponent();
}
public MyForm2(MyForm1 form1)
{
this.form1 = form1;
}
private void button1_Click(object sender, EventArgs e)
{
form1.SetImage(yourImage);
}
}
You can very simply do this.
At first change your code(in Form1) that show Form2 to looks like this:
<variable-of-type-Form2>.ShowDialog(this);
or if you dont want form2 to be modal
<variable-of-type-Form2>.Show(this);
Next when you got path to image, you can access pictureBox like this
((PictureBox)this.Owner.Controls["pictureBox1"]).Image=Image.FromFile(<filename>);
Assume that you have PictureBox on Form1 with name "pictureBox1"
Ideally, you want to structure your code in a ModelViewController pattern. Then, you simply have a reference in your model to the image in the picture box. When interacting with the OpenFileDialog in Form2, you would call your model adapter interfaces hooked into the views (Form1 and Form2) to change the image being held in the model. In short, you need a callback from the view to the model. If you don't want to redesign your code to be MVC, simply have a shared object holding the image reference that both Form1 and Form2 receive in their constructors, so they can both modify it.

"An object reference is required for..." when trying to access default form button

I am trying to access a button on my default created form from a different thread in the same application. However, I get the error
An object reference is required for the non-static field, method, or property 'BElite.Form1.testButton1'
where Form1 is the default form created and testButton1 is the test button that I want to change the text of from my thread.
I understand that I somehow need to get a reference to the Form1 object... but i have no idea how!
Please help.
You are referencing testButton1 like it was a static field instead of an instance field. You need to be able to access the instance of the form. You can do this like this:
public partial class Form1 : Form
{
public static Form1 Instance { get; private set; }
public Form1()
{
InitializeComponent();
if (Instance != null)
throw new Exception("Only one instance of Form1 is allowed");
Instance = this;
FormClosed += new FormClosedEventHandler(Form1_FormClosed);
}
void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Instance = null;
}
public Button TestButton1 { get { return testButton1; } }
}
Because controls on the form are protected by default, you have to make the button accessible. You do this using the TestButton1 property.
Now you can access the textbox using BElite.Form1.Instance.TestButton1.
Two notes:
This only works if you always have a single Form1, for example when Form1 is the main form of your application;
Please note that accessing these controls from a different thread must be done using Control.Invoke() or Control.BeginInvoke(). See the documentation on these methods on why and how.
You can access the button using BeginInvoke() with the following sample:
Form1.Instance.BeginInvoke(new Action(() =>
{
Form1.Instance.TestButton1.Text = "My new text";
}));
Everything in the block ({ ... }) is safe.

Categories