How to copy string value from Form2 to Form1 label - c#

I have Form1 that has a toolStripStatusLabel. Then Form2 that has button and is there string with value ( Hello ). I need if i click on the button, show value "Hello" to toolStripStatusLabel in Form1. toolStripStatusLabel is set to public.
This show me :
Cannot implicitly convert type 'string' to 'System.Windows.Forms.ToolStripLabel'
public partial class form2 : Form
{
public form2()
{
InitializeComponent();
}
Form1 form = new Form1();
string example = "hello";
private void button1_Click(object sender, EventArgs e)
{
form.toolStripLabel1 = example;
}
}
}

Well you'd need to say formtoolStripLabel1.Text = example; rather than what you said. However, this will not affect the one from the original instance of Form1. If you wanted to affect the original instance of Form1, you'd make the tooStripLabel public static rather than just public so that all classes can affect it immediately.

You have to set the Text property in the ToolStripLabel object.
form.toolStripLabel1.Text = example;
Take a look at this.

You should you:
form.toolStripLabel1.Text = example;
instead of:
form.toolStripLabel1 = example;
And you might want to take a look at this: http://www.codeproject.com/Articles/14122/Passing-Data-Between-Forms
If you want to share data between 2 forms

Related

Fully access a control from another Form

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.

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.

c# - Use the same element in different forms

I am doing a registration system. In this system I use a modal, another form that is displayed when the user clicks a button.
To show the form, I use:
private void btnShowModal_Click(object sender, EventArgs e)
{
AddUserForm form = new AddUserForm();
form.Show();
}
This works great to show the form. Now this is my problem: if I create one label in this form and try to use it for reference in the primary form I get the error that it does not exist in context. Example, I've created label1 in the AddUserForm. Now I will try to use the same label in Form1 to change the text:
label1.Text = "I was created in AddUserForm and now I'm at Form1!";
...but this don't work, I get the error:
The name 'label1' does not exist in the current context.
How I can use elements in both forms? I need to add a reference? How? Thanks all in advance!
Create a Base form that creates the label. Each form can then inherit from the base form and share it that way.
public class BaseForm : Form
{
//define label
}
public AddUserForm : BaseForm
{
}
In your AddUserForm, create this property:
public string LabelText
{
get { return label1.Text; }
set { label1.Text = value; }
}
Then in your Form1, simply add this line after you create the AddUserForm instance:
form.LabelText = "I was created in AddUserForm and now I'm at Form1!";
More generally, while you could have exposed the field (it's private by default), doing so is a bad idea. Wrapping form elements in properties gives you control over exactly what the outside world can and cannot change. For example, you may not want other classes being able to change the size, location, font, etc. of the label. Or maybe you do, but if so then you add properties specifically for those things you want to be able to be changed.
I think you can try like this,
Form1.cs
private void btnShowModal_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(ref this.label1);
frm.ShowDialog();
}
Form2.cs
Label labelOne = null;
public Form2()
{
InitializeComponent();
}
public Form2(ref Label lbl)
{
InitializeComponent();
labelOne = lbl;
}
private void Form2_Load(object sender, EventArgs e)
{
labelOne.Text = "A";
}
Hope it solves!

getting textbox value from another form

I have an TextBox named pass in Form1 that I need to get the value of in form2. I tried this:
public partial class Form1 : Form {
public string GetPass() {
return pass.Text;
}
}
public partial class form2 : Form {
//...
MessageBox.Show(new Form1().GetPass());
}
The above code returns an empty string, why?
You are not showing your actual code as evidenced by the syntax errors etc. - the only logical explanation for your problem is that you are not passing the reference to Form1 correctly to Form2, but create a new form instead - that new form would have the empty textbox.
To further help you, please show how you pass the reference to your Form1 in your actual code.
Edit:
Is see your edit now and above is exactly the problem. You have to pass a Form1 instance to form2 instead of creating a new one, i.e.:
public partial class form2 : Form
{
private Form1 form1;
public form2(Form1 otherForm)
{
form1 = otherForm;
}
public void Foo()
{
MessageBox.Show(form1.GetPass());
}
}
Define one string variable as Public in declaration section
for ex. we have a form with name "frmOne"
public string strVar = string.Empty;
Now, assign the value of TextBox of "frmOne" to that variable from where you are getting the value of Textbox.
for ex.
strVar = Textbox1.Text.ToString();
Now in another form say "frmTwo", you will get access the value of that textbox of "frmOne" something like that (where you want to get the value) :
frmOne frm = new frmOne();
string strValue = frm.strVar;
So, finally strValue local variable of frmTwo contains the value of Textbox of frmOne.
You are creating a NEW form1 where the textbox is likely to be blank, and calling GetPass() on that empty form. You need an instance of the already-opened form1 where the textbox might have a value.
Because you are creating a new instance of Form1 each time you call GetPass().
You need to get the instance of the opened form1 one way or another, and call GetPass on it:
form1.GetPass();
If there is no specifics on the order of creation of form1 and form2, you can use the following to get the instance of form1:
foreach (Form openedForm in Application.OpenForms) {
if (openedForm.GetType() == Form1) {
MessageBox.Show(openedForm.GetPass());
}
}
It's returning empty because you're creating a new instance of the form. Assuming that Form1 is already open somewhere, you need to retrieve the existing instance of Form1 and pull the value from there.
hi you can write this :
public partial class Form1: Form
{
public Form1()
{
InitializeComponent();
}
internal Form2 F2=new form2();
private void CommandBarButton1_Click(object sender, EventArgs e)
{
MessageBox.Show(f2.TextBox1.Text);
}
}

Categories