This question already has answers here:
passing variables into another form
(5 answers)
Closed 8 years ago.
I'm working on a multi Windows Form project, where the value selected from the Combobox on one form should enable a ComboBox on another form. Could anyone tell me how to do that?
On the Combobox on Form1, some of the items on the list are "Mango", "Banana", "Papaya", "Orange".
On the Combobox on Form2, the values are 1, 2, 3, 4. So if a user select Mango or Papaya on Form 1, the combobox on form2 will be enabled for the user to select a number. Otherwise, the combobox will remain disabled.
Here's what I do.
I created a public class with 2 properties for both forms.
public class FormValues
{
private bool _secondcbb = false;
private string _firstcbb = "";
public bool SecondCbb
{
get
{
return _secondcbb;
}
set
{
_secondcbb = value;
}
}
public string FirstCbb {get; set;}
}
// ..... On Form1:
Form2 frm2 = new Form2();
FormValue val = new FormValue();
private void ComboBox1_SelectedIndexChanged(whatever inside)
{
if(ComboBox1.SelectedText == "Mango")
{
val = true;
frm2.ComboBox2 = val;
}
}
I don't do anything on Form2. Except adding the control and set the Combobox to be disabled.
Make public static method on Form 2 that will change comboBox state if comboBox item on Form 1 is selected like this:
public static void ChangeState(bool state) // Method on Form 2
{
comboBox2.Enabled = state;
}
Enable comboBox2 when item is selected:
private void comboBox1_SelectedIndexChanged(whatever inside)
{
if(comboBox1.SelectedText == "Mango" || comboBox1.SelectedText == "Papaya")
frm2.ChangeState(true);
else
frm2.ChangeState(false);
}
Why are you not setting the enabled property of the ComboBox2?
Like this:
frm2.ComboBox2.Enabled = true;
This way you also don't need the FormValue, or am I wrong?
It's not really clear what your FormValues class is doing, but I don't think it's necessary in the first place. In your Form2 create a method which does what you need that form to do:
public void SomeMethod()
{
// enable the control?
// edit the control?
}
This would allow anything which holds a reference to an instance of Form2 to manipulate it using the exposed functionality. Provide such a reference to Form1. Either it internally instantiates the instance of Form2 or it requires one as a constructor argument. Either way, Form1 should have a reference to an instance of Form2:
private Form2 Form2Instance { get; set; }
Then in your control's handler in Form1 you simply invoke the functionality on that instance:
this.Form2Instance.SomeMethod();
Related
I am trying to pull the data from a datagridview value in form1 to a textbox in form2 .
Form 1;
public string xxx;
public string GetX()
{
return xxx;
}
private void addADocumentToolStripMenuItem_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows != null)
{
xxx = dataGridView1.CurrentRow.Cells["Name"].Value.ToString();
AddDocumentForm adf = new AddDocumentForm();
adf.ShowDialog();
}
else
{
MessageBox.Show("Please choose a record.");
return;
}
}
In Form 2 trying to pull the xxx value into textbox;
using (Form1 f= new Form1())
{
string result= f.GetX();
txtSavedDocumentID.Text = result;
}
In Form2, you are creating a new instance of Form1:
using (Form1 f= new Form1())
As I can't see your whole code, I might be wrong - but I think it is very likely that this is not what you want.
What you actually want is to call GetX() on an existing instance of Form1.
Now you need some way to know the correct instance of Form1 on Form2. One easy possibility is, but only if you will always just use one instance of Form1, to expose a static property on Form1 that will provide a singleton instance of it to the outside world:
public class Form1
{
// ...
public static readonly Form1 Instance {get; private set};
public Form1()
{
Instance = this;
}
// ...
}
In Form2, instead of creating a new instance with your using statement, you'd access it like this:
string result = Form1.Instance.GetX();
txtSavedDocumentID.Text = result;
Now be aware that if your application has the possibility to have multiple instances of Form1 open, this won't work and will have bad side effects. In this case, another approach is needed. But I hope you got the idea now what might be wrong and you can work it out.
Edit: While this will solve your issue, hopefully, I want to add that it's not a very good approach having your Forms need to know about each other. You should have some model classes in the background where your Forms can read and write data on, without the need to interact with each other directly. But exploring this further would be out of scope of this question.
changed Form2 ;
public Form2(string qs)
{
InitializeComponent();
textBox1.Text = qs;
}
In Form1;
get the text from combobox and pass it to form2 ;
{
var xxxx = (cbxEmployeeName.GetItemText(cbxEmployeeName.SelectedItem));
Form2 f = new Form2(xxxx);
f.Show();
}
After entering in the appropriate text and pressing enter, I want txtbA text in Form1 to display in txtbB in Form 2.
I already have the key events code written, but I can't seem to figure out the rest.
Visual basic seems to be more straightforward with this, and I am new to C#.
This is using WinForms.
I am really only familiar with visual basic's way of handling this:
txtbA.text = My.Forms.Form2.txbB.text
Thank you for any help you can give!
You can use a static variable
In Form1
public static string txtbAtext
{
get { return txtbAtext ; }
set {txtbAtext = value; }
}
OnTextChanged Event
txtAtext = txtA.Text;
In Form2
Form1 f1 = new Form1();
txtbB.Text = Form1.txtAText;
The simpliest and not very elegant way is to do ist like this:
Make a property in the second form, that can hold a Textbox and set the Text property in the TextChange event of the property in Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public TextBox TextBoxWithSameText { get; set; }
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (TextBoxWithSameText != null)
TextBoxWithSameText.Text = textBox2.Text;
}
}
All you have to do now is to set the property to the Form1.textbox1 when the second form (Form2) is created:
Form2 form = new Form2();
form.TextBoxWithSameText = textbox1;
In order to exchange strings between two Forms classes, you can use a third class. Once added to your project, you need to instantiate this new Class1 in your Form1 and Form2:
Class1 class = new Class1;
Make sure Class1 has a constructor. Now, you can create properties in your Class1, with get and set properties:
public string TextA
{
get
{
return textA;
}
set
{
textA = value;
}
}
You can then call these properties from any other class that has instantiated your Class1, like so:
class.TextA = txtbA.Text;
In order to show the text in the other textbox, you need an event to trigger changing the txtbB.Text value. You could use txtbA.ValueChanged event, or a button with a Click event. You should figure out what event is most appropriate for your project.
I hope this helped! Good luck.
Based on your comment:
Right, Form1 will open an instance of Form2 upon pressing the Enter
key. Thanks!
You can setup Form2 to receive the initial value for the TextBox via its Constructor:
public partial class Form2 : Form
{
public Form2(string InitialValue)
{
InitializeComponent();
this.txtbB.Text = InitialValue;
}
}
Then in Form1 you'd do something like:
Form2 f2 = new Form2(this.txtbA.Text);
f2.Show();
I need to interact with controls on other forms. Trying to access the controls by using, for example, the following...
i am accessing Backupform control from form2
in backupform : I have defined like this....
public partial class BackupForm
{
public bool ControlIsVisible
{
get { return this.btnrestore.Visible; }
set {this.btnrestore.Visible = value; }
}
public BackupForm()
{
InitializeComponent();
cbbackupforms.SelectedIndex = 0;
// btnrestore.Enabled = false;
}
}
i made the btnrestore properties visible = true; and modifiers = private in designer of backupform
and in form2 i am accessing the btnrestore visible property
public partial class form2
{
private Forms.BackupForm backs;
public form2()
{
InitializeComponent();
backs = new Forms.BackupForm();
}
public void restore()
{
backs.ControlIsVisible = false;
}
}
but i am not able to visible false for the button , would any one pls suggest any solution for this.....
Many thanks in advance
You can supply a reference to the instance of the first form, and use that reference to set properties of objects on that form. When you cast the object to Form1, the properties will be accesible.
When are you calling your Restore() method? Also, if all the Restore() method does is set the button's visible property on the seperate form, why not encapsaluate that method within your BackupForm object and call it using backs.Restore()?
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do you pass an object from form1 to form2 and back to form1?
I'm used to passing variables between windows forms by simply passing them as a parameter.
Now I have a form that is already open (let's call it FormMain), and another form that should act like a dialog (FormTask). The user cannot interact with the main form until he has filled in the information on FormTask. FormTask simply contains a single textbox, and the value of this textbox should be returned to FormMain, and kept track of as a variable. FormTask requires a parameter exerciseType. When FormTask opens it checks the value of this parameter and sets the default value of the textbox accordingly. This already works, I'm just kind of clueless on how to return my string value to the already open MainForm.
These dialogs only seem to be able to return DialogResults, which isn't what I'm after. I'm not too experienced either, and I'd rather avoid fumbling around to make my own custom dialog.
FormMain:
FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoker.ShowDialog();
FormTask:
private void button1_Click(object sender, EventArgs e)
{
string opgave = textBoxOpgave.Text;
// return string value to MainForm here
}
Create public property in FormTask
public string Opgave { get {return textBoxOpgave.Text;}}
And check it after ShowDialog();
FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoer.ShowDialog();
formOpgaveInvoer.Opgave; // here it is
The simplest way to do this is to add a public property to your form class to return the string.
public string opgave
{
get;
private set;
}
Assign to this property as your dialog closes and then read the property from the code that called ShowDialog():
private void button1_Click(object sender, EventArgs e)
{
opgave = textBoxOpgave.Text;
}
...
FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoker.ShowDialog();
DoSomething(formTask.opgave);
Forms are just normal classes. This means, you can create properties in them.
So: Create a property and assign the value to it.
Add a property to the FormTask for example String1 like
public string String1 {get; set;}
Set String1 value in button1_Click for example,
You can access that property in MainForm like
FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoer.ShowDialog();
string str = formTask.String1;
In Visual C# when I click a button, I want to load another form. But before that form loads, I want to fill the textboxes with some text. I tried to put some commands to do this before showing the form, but I get an error saying the textbox is inaccessible due to its protection level.
How can I set the textbox in a form before I show it?
private void button2_Click(object sender, EventArgs e)
{
fixgame changeCards = new fixgame();
changeCards.p1c1val.text = "3";
changeCards.Show();
}
When you create the new form in the button click event handler, you instantiate a new form object and then call its show method.
Once you have the form object you can also call any other methods or properties that are present on that class, including a property that sets the value of the textbox.
So, the code below adds a property to the Form2 class that sets your textbox (where textbox1 is the name of your textbox). I prefer this method method over making the TextBox itself visible by modifying its access modifier because it gives you better encapsulation, ensuring you have control over how the textbox is used.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string TextBoxValue
{
get { return textBox1.Text;}
set { textBox1.Text = value;}
}
}
And in the button click event of the first form you can just have code like:
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.TextBoxValue = "SomeValue";
form2.Show();
}
You can set "Modifiers" property of TextBox control to "Public"
Try this.. :)
Form1 f1 = (Form1)Application.OpenForms["Form1"];
TextBox tb = (TextBox)f1.Controls["TextBox1"];
tb.Text = "Value";
I know this was long time ago, but seems to be a pretty popular subject with many duplicate questions. Now I had a similar situation where I had a class that was called from other classes with many separate threads and I had to update one specific form from all these other threads. So creating a delegate event handler was the answer.
The solution that worked for me:
I created an event in the class I wanted to do the update on another form. (First of course I instantiated the form (called SubAsstToolTipWindow) in the class.)
Then I used this event (ToolTipShow) to create an event handler on the form I wanted to update the label on. Worked like a charm.
I used this description to devise my own code below in the class that does the update:
public static class SubAsstToolTip
{
private static SubAsstToolTipWindow ttip = new SubAsstToolTipWindow();
public delegate void ToolTipShowEventHandler();
public static event ToolTipShowEventHandler ToolTipShow;
public static void Show()
{
// This is a static boolean that I set here but is accessible from the form.
Vars.MyToolTipIsOn = true;
if (ToolTipShow != null)
{
ToolTipShow();
}
}
public static void Hide()
{
// This is a static boolean that I set here but is accessible from the form.
Vars.MyToolTipIsOn = false;
if (ToolTipShow != null)
{
ToolTipShow();
}
}
}
Then the code in my form that was updated:
public partial class SubAsstToolTipWindow : Form
{
public SubAsstToolTipWindow()
{
InitializeComponent();
// Right after initializing create the event handler that
// traps the event in the class
SubAsstToolTip.ToolTipShow += SubAsstToolTip_ToolTipShow;
}
private void SubAsstToolTip_ToolTipShow()
{
if (Vars.MyToolTipIsOn) // This boolean is a static one that I set in the other class.
{
// Call other private method on the form or do whatever
ShowToolTip(Vars.MyToolTipText, Vars.MyToolTipX, Vars.MyToolTipY);
}
else
{
HideToolTip();
}
}
I hope this helps many of you still running into the same situation.
In the designer code-behind file simply change the declaration of the text box from the default:
private System.Windows.Forms.TextBox textBox1;
to:
protected System.Windows.Forms.TextBox textBox1;
The protected keyword is a member access modifier. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member (for more info, see this link).
I also had the same doubt, So I searched on internet and found a good way to pass variable values in between forms in C#, It is simple that I expected. It is nothing, but to assign a variable in the first Form and you can access that variable from any form. I have created a video tutorial on 'How to pass values to a form'
Go to the below link to see the Video Tutorial.
Passing Textbox Text to another form in Visual C#
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
TextBox txt = (TextBox)frm.Controls.Find("p1c1val", true)[0];
txt.Text = "foo";
}