how to change a control property from another form - c#

I have two forms in a windows form application. lets call them "first form" and "second form".
i want by clikcing on a button on second form, change the property of one of the controls of the first form. i've defined an event for this. by that i mean when i click on the second form's button, a method within the first form is called. here's the method:
// changes the visibility of the specified control
public void change_visibility()
{
this.new_customer_label.Visible = true;
}
but when i set a breakpoint on this method and check the value after it is executed. the property has't changed. what is wrong? thanks in advance
note: on the second form button's click event, i also close the form.

So firstly, Open up Form1.designer.cs and change the control to public
Form1 this will open Form 2.
Form2 frm2 = new Form2();
frm2.Owner = this;
frm2.Show();
Form2 this will change the property of a control in Form 1
(this.Owner as Form1).label1.Visible = true;

Here is an example of what you can do:
class Form1 : Form {
private Label labelInForm1;
public string LabelText {
get { return labelInForm1.Text; }
set { labelInForm1.Text = value; }
}
}
class Form2 : Form {
Form1 form1; // Set by the property
private Form1 Form1 {
get { return form1; }
set { form1 = value; }
}
private ChangeVisibility()
{
Form1.labelInForm1.Visible = true;
}
}

"note: on the second form button's click event, i also close the form."
Then it would probably be a better design to display the second form with ShowDialog() instead of Show(). Something like:
Form2 f2 = new Form2();
f2.ShowDialog(); // code STOPS here until "f2" is closed
this.new_customer_label.Visible = true;

By default, the designer generates code in the 'Form1.Designer.cs' class. In there, you can see that all the controls are set private, change them to public and then try again...

As you will search this problem on internet you will find different solutions but I think the best solution is to make controls public then you can access these controls from any form.
Follow these instructions.
Open your desire form whose control properties you want to access
Open Form.Designer.cs
Change the desire control class to public
Go to the main form where you want to access or change property
Write this code
Form Form2 objForm=new Form2();
Now access your control property here
objForm.new_customer_label.Visible=true;
I hope this will be helpful to you!!!

Related

Reloading the form instead of making a new one / accessing textbox outside of form

I am having a problem controlling a textbox. I need to change a value from outside of Form1.cs where the textbox is located for this I have found this snippet.
public void UpdateText(string newValue)
{
torrent_name0.Text = newValue;
}
this allows me in theory to control the textbox outside of Form1.cs, but here comes the problem, every time I want to access it I create a new instance of Form1 instead of using the old one and refreshing it.
Form1 frm = new Form1();
frm.UpdateText("aaaaaaaaaaaa");
frm.Show();
am I missing something? is there a better way to do this? I have tried multiple ways to update the new form but got nowhere.
Bokker,
You will have to have a reference to the singular form1 to which all things refer.
If this is a child form, then as Aybe commented, create a public member of your mainform and name it something.
Public Form myForm1;
You probably have some Event by which you would like Form1 be launched...
A Button click, menu item, toolbar item, etc. In that event you will have to check if the form exists and create if required.
private SomeEvent() {
if (myForm1 == null)
{
myForm1 = new Form1();
myForm1.Show(this);
}
myForm1.UpdateText("some text");
}
Alternatively, you could create the form in the Form Load event, just so long as you create the form prior to attempting the myForm1.UpdateText()
If you follow this paradigm, you are creating myForm1 as part of the main form, best practice says you should also dispose of the form in your main form Closing Event.
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (myForm1 != null)
{
myForm1.Close();
myForm1.Dispose();
}
}
This is all off the top of my head, so it might not be perfect.
In that case you can pass the instance of form in the method as argument and make the changes like
public void UpdateText(string newValue, Form1 frm)
{
frm.torrent_name0.Text = newValue;
}

Passing values between a class and a form

I'm pretty new to C# - but it all went quite well - to this point.
I start with a form and a class which does most of the work (non static and in the program part). I instantiate an object of the class in form 1 and do a log in.
Then I switch over to the next form, form2. Actually, the the class does that. I have a method there, that contains the line:
this.f2 = new Form2();
and then:
f2.Show();
f2 is a class member of the type Form2 - and all just works fine - up to this point.
This Form2 just consists of a big text box in which I want to display network events. The event handler works just fine - but the reference to the form just doesn't seem to work. If I do
f2.tetBox1.Text = "Some text";
it just won't change the the text in the text box.
What am I doing wrong here?
Here is a more detailed description of what I'm doing:
Form1 passes some log in information to myProg, being an instance of MyClass. If the login was successful, Form1 calls myProg.makeForm();
This is what the method in MyClass looks like:
public void makeForm() {
this.f2 = new Form2();
f2.Show();
this.sendString("start f2");
}
This is MyClass.sendString():
private void sendString(string text) {
SystemSounds.Beep.Play();
this.f2.setTextBox(text);
}
This calls, as you see, setTextBox() of Form2 - which I implemented as proposed here. The strange thing is, that up to this point all works well. The Form2 gets shown an textBox1 contains "start f2" - as expected. But when an event comes in, the text in textBox1 doesn't change. the beep get played all right - so the method sendString() gets called alright.
One thing I have observed: If the beep line is placed after the call to this.f2.setTextBox(text);, it doesn't get played if the method is called from the event handler.
f2, btw., is a private member of MyClass:
private Form2 f2;
Any control created by the designer (e.g. dropped from the Toolbox at design-time) is automatically set as private. Therefore, you can't access it from another form.
You don't want to start messing with the designer, instead - create a property on your Form2 which will allow you to modify the text of the Textbox from Form1.
A short example is something like this:
Form2:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
// When modifying the Text property it will change the text in textbox1
public string Text
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
}
Then, in Form1:
Form2 frm2 = new Form2();
frm2.Text = "123"; // Uses the public Text property declared in Form2
frm2.Show();
By default a textbox is private when you place it via the designer, which means you can't access textBox1 from outside of Form2 (it's only 'visible' to code within the Form2 class). You could change the textbox to be internal or public (which would let you do the following (from Form1):
f2.tetBox1.Text = "Some text";
BUT that would be exposing parts of Form2 which only Form2 should really know about...so it isn't the cleanest solution (though it would be likely the quickest))
A better solution might be to create a method or property (internal or public) in Form2 which will set the text value. E.g.:
internal void SetText(string value)
{
textBox1.Text = value;
}
As the method (or property) resides in Form2, it has access to the text box, so it can set the value while textBox1 is still private.
It's safer exposing this method to 'external' code (as opposed to making the textbox visible to them) as all they can do is change the text - whereas exposing the whole textbox might let callers try to change background colour, etc.

Changing a label's text in another form in C#?

I have a label called LabelX1. This is on form2. On form1, i have a button. I want the button's text to be transferred to the other form's label. I have tried
form2 frm2 = new form2();
frm2.labelX1.Text = this.button1.text;
But it does not work. Is there an easy, straight forward way of doing this?
You need to expose your label or its property.
In form 2:
public string LabelText
{
get
{
return this.labelX1.Text;
}
set
{
this.labelX1.Text = value;
}
}
Then you can do:
form2 frm2 = new form2();
frm2.LabelText = this.button1.text;
You could modify the constructor of Form2 like this:
public Form2(string labelText)
{
InitializeComponent();
this.labelX1.Text = labelText;
}
then create Form2 passing in the text:
Form2 frm2 = new Form2(this.button1.text);
Or you can do this >>
((Label)frm2.Controls["labelX1"]).Text = "test";
inside form2 write this
public void ChangeLabel(string s)
{
labelX1.Text = s;
}
then where you create Form 2 do this
form2 frm2 = new form2();
frm2.ChangeLabel(this.button1.text);
Is there an easy, straight forward way of doing this?
Easiest way is to make labelX1 a public member of form2. The issue you're having is because from Form1 code form2.labelX1 isn't visible. In form2 designer you can go to properties of labelX1 and set it's visibility to public/internal.
Better approach would be to expose labelX1.Text as a property which can be set in code outside the class.
form2 frm2 = new form2();
((Label)frm2.Controls["labelX1"]).Text=button1.Text;
frm2.Show();
the only think you have to do is to put the label of the other form as public
for instance:
Form1:
public System.Windows.Forms.Label txtInfo;
then in Form2
Form1 frm =new Form1();
frm.txtInfo.text="....."//you have access because is public
You can make labelX1 public, and it will work, but there is a better way to do this:
http://www.codeproject.com/Articles/14122/Passing-Data-Between-Forms
I changed my parent window property to the following code:
this.MdiParent.Controls["label1"].Text = "test";
If you are needing to access the form2 from elsewhere in your code (like a button press for instance) you will not be able to see the instance of the form you create. To solve that I create a public instance to hold a reference to it like:
public form2 form2_pub;
Then after you create it you assign the new one to your public instance:
form2 frm2 = new form2();
frm2.Show();
form2_pub = frm2
Now you can reference form2_pub throughout your routines.
Works for me at least.
Remember, in your setter you can run whatever other code you want.
For instance, I use the following to show what I want on another form by just setting show_scanning to true:
public bool show_scanning //turns on the scanning screen
{
set
{
scanning_pnl.Visible = true;
notReady_pnl.Visible = false;
timer1.Enabled = true;
}
}
Generally the controllers are private. That is why you unable to access it from another form. Above mentioned ways such as passing data through parameters etc are so correct. There is one another method,
Go to your form Form2.Designer.cs
private System.Windows.Forms.Label labelX1;
Change 'private' into 'public'.
Now the labelX1 is visible to outside.
The another approach is
Just change the modifier property of label or text to public and now it allows to access the content of form1 textbox to label on another form
So the code is
private void button1_click(){
Form2 obj1 =new Form2();
Obj1.show();
Obj1.label1.text="welcome"+textbox1.Text;
}
Do you have exception? You can make public property on form2, with setter to set text on the label, or make labex1 access modifier public and set it directly. It should work.

c# getting value from other form

Situation i have: textbox(to input your name) on form1. From that form1 on button click i go to form2. From form2 button click to form3. On form3 on button click i need to writte me in empty textbox value from textbox on form1 that user wrote down.
example: on form1 in textbox1 i write my name "Djuzla". When i go to form3 and click button to see what name i wrote in form1 it should show in empty textbox3 form3 "Djuzla".
I'm stuck with this few hours now, and it stupid problem but i have no idea what to do next.. tried all from zillion theards on net :p
You could modify the constructor of the form to take one more argument to hold the value of the textBox.
Store the value in a property. If you are developing for asp.net, use session or ViewState. Did I understand your question?
You may access the PreviousPage property from the page, or set a session variable (or a cookie) and then retrieve it on page load etc. but the most straightforward solution is to use the PreviousPage property on the page to access the data from previous page.
I've answered similarly... Since you are going from Form 1 to 2 to 3, you could basically take the same approach in this solution to cascade the value out and back as needed, not just one way...
My Other Solution to similar question...
The solutions that pass a value around can get quite sloppy because there's no guarantee that the value inside the textbox won't change after you've already passed it somewhere. Instead, it's more sensible to pass a function around which resolves the value from the TextBox when called, which will result in always getting the lastest value.
void button1_Click() {
form2 = new Form2(() => textBoxName.Text);
}
class Form2 : Form {
...
public Form2(Func<String> nameResolver) {
form3 = new Form3(nameResolver);
}
void button1_Click(...) {
form3.Show()
}
}
class Form3 : Form {
Func<String> nameResolver;
public Form3(Func<string> nameResolver) {
this.nameResolver = nameResolver;
}
void button1_Click(...) {
this.textBoxName = nameResolver.Invoke();
}
}
If you end up requiring more than one or two components shared between the various forms, it might be better to simply pass the forms themselves to child forms. Eg.
void button1_Click(...) {
form2 = new Form2(this);
}
class Form2 : Form {
Form1 parent;
public Form2(Form1 parent) {
this.parent = parent;
}
void button1_Click(...) {
form3 = new Form3(parent);
}
}

Fill Identity Of WinForms Into Textboxes

I have Three Forms as below:
Form1
Form2
Form3
The Form1 and Form3 are communicating with Form2. I want If Form1 visited to Form2 than
Form1 Should leave it’s identity to Form2’s textbox1. If Form3 visited to Form2 than Form3
should leave it’s Identity to Form2’s textbox2.
Is it possible?.
Here is Visted Means as below.
By Form1
Form2 f2= new Form2();
f2.Show();
By Form3
Form2 f2= new Form2();
f2.Show();
And Identity Like "Form1" and "Form3"
I believe you are asking for the form that opens Form2 to set some specific value to the textbox. You could have a property on Form2 that sets the textbox text.
public partial class Form2 : Form
{
/*.......*/
public string Identity
{
set
{
textbox1.Text = value;
}
}
}
Then in Form1 or Form3:
Form2 form2 = new Form2();
form2.Identity = this.Name;
form2.Show();
The best thing to do is overload the Show method for each of your forms to accept something like a "previous form" parameter that will serve as a reference to the caller (you could do this either as a Form object, whose properties you could then access, or simply as a String). Then, wherever you show a second form from an existing form, you pass information about the existing form into the Show method for the second form. The second form's Show method would take care of updating its textbox with the name of the form that displayed it.
For example, each form would contain an overloaded Show method:
public void Show(Form previousForm)
{
//Set the textbox on this form to contain the name of the calling form
myTextBox.Text = previousForm.Name;
//Call the base class's method to show this form
base.Show();
}
And you would show one form from another by calling its overloaded Show method:
private void ShowOtherFormButton(object sender, EventArgs e)
{
//Create a new instance of the form you want to display
Form2 myOtherForm = new Form2();
//Show the other form, passing the calling form as a parameter
myOtherForm.Show(this);
}
This way, no form is responsible for or even allowed to update controls contained by another form. You don't have to expose any additional properties or remember to call any additional methods on the forms you want to show—it's built right into the Show method that you have to call anyway.
Alternatively, you could overload each form's constructor in the same way, but that won't work if you want to be able to move between existing instances of each form. You'll only be able to specify information about the previous form when you're creating a new instance of each form.
You will need a reference to the caller. You can do this by overriding the constructor of the Form.
public partial class Form2 : Form
{
Form _caller;//Caller form
//Default constructor
public Form1()
{
InitializeComponent();
}
public Form1(Form caller)
{
InitializeComponent();
this._caller = caller;
textbox2.Text = caller.Name;
}
}
All you have to do now is call Form2 using the new constructor:
Form2 form2Instance = new Form2(this);
form2Instance.Show();
Whichever form will call Form2, will now have it's name written on textbox2 of Form2
You need to pass data between the window forms(ie.,the name of the form in this scenario)so that you can get it in Form2.
Refer the lint to pass data between window forms: http://www.vbdotnetheaven.com/UploadFile/thiagu304/passdata12262006073406AM/passdata.aspx

Categories

Resources