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;
Related
This question already has answers here:
Use a variable from another method in C#
(2 answers)
Closed 2 years ago.
I am trying to build a program, but I realized I can't access a certain variable because it's created in another method.
How do I transfer a variable to another method?
This is an example of what I'm trying to do:
namespace Example
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string text = textBox1.Text;
}
private void label1_Click(object sender, EventArgs e)
{
// Get the "text" variable and use it
label1.Text = text;
}
}
}
Your example has a Form named Form1 that has a Button named button1, a TextBox named textbox1 and a Label named label1.
The scenario you are attempting is:
user enters some text into textbox1
user clicks on button1, this will save the current value from textbox1
user clicks on label1, this will display the value that was stored in the previous step
It is important to understand that in this scenario we are not trying to pass a value between 2 methods because the button click and the label click can occur independently of each other, so really this is like the memory store (M+) and memory recall (MR) buttons on calculator.
To achieve this storage you should create an instance variable (sometimes referred to as a member variable) on the Form1 class, this will be accessible to the other methods on the same instance of the Form1 class.
See Working with Instance and Local variables for a practical explanation
Create a field or a property to store the value, for your specific example either would work, however to become familiar with C# techniques I would recommend you start with a property, as that better encapsulates your scenario of storing the value for later use and later to potentially augment how and where the value is actually stored.
See What is the difference between a field and a property?
for a healthy discussion
Until you need to change the implementation, you can simply use an Auto-Property
public string StoredText { get; set; }
Now in the click event handler of button1 we can set the value of the StoredText property on the Form1 instance
private void button1_Click(object sender, EventArgs e)
{
this.StoredText = textBox1.Text;
}
set is a term we use for saving a value into a property in c#
Note the use of the this keyword, it is optional in this case, or can be inferred by the compliler, it indicates that we want to reference a member on the instance of the class, not a variable that might have the same name within the same method scope of the line of code that is executing.
Finally in the click event handler of label1 we can get the value that was previously stored in the StoredText property in the Form1 instance.
private void label1_Click(object sender, EventArgs e)
{
// Get the "StoredText" variable and use it
label1.Text = this.StoredText;
}
get is a term we use for accessing a value from a property in c#
this is not required, but can be helpful to understand that we are accessing a member that is outside of the current method scope.
Together this looks something like:
namespace Example
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>Saved value from see <see href="textBox1"/></summary>
public string StoredText { get; set; }
private void button1_Click(object sender, EventArgs e)
{
this.StoredText = textBox1.Text;
}
private void label1_Click(object sender, EventArgs e)
{
// Get the "StoredText" variable and use it
label1.Text = this.StoredText;
}
}
}
What you may not have noticed is that textBox1 and label1 are themselves infact instance variables that are initialized in a separate code file when InitializeComponent() is executed in the constructor.
For this reason you do not need to store the value at all and you could simply re-write the client event handler for button1 to write directly to label:
label1.Text = textBox1.Text;
It is possible to pass variables directly between methods without an intermediary store, this is a lesson for another day and will involve return statements and/or parameters on your methods.
In this scenario however, neither return or additional parameters on these methods cannot be used because these are event handlers that need a specific method signature to operate as expected.
You are almost there. It is a common practice in object-oriented programming to have private variables in a class, in order to share states. Add a variable in your class. It will be available in all methods and can be used to shared data between them (this is one approach of many):
namespace Example
{
public partial class Form1 : Form
{
private string inputText { get; set; }
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
inputText = textBox1.Text;
}
private void label1_Click(object sender, EventArgs e)
{
// Get the "text" variable and use it
label1.Text = inputText;
}
}
}
From what i've read so far i've done this:
On my first form:
public partial class FPrincipal : Form
{
List<Grua> ListaGruas = new List<Grua>();
List<Semirremolques> ListaSemirremolques = new List<Semirremolques>();
List<Clientes> ListaClientes = new List<Clientes>();
// this is the menu strip i click to create my new form,
// send my list and add my values
private void miEquipoCargar_Click(object sender, EventArgs e)
{
EquiposCargar FormEquiposCargar = new EquiposCargar(ListaGruas);
FormEquiposCargar.ShowDialog();
}
}
And on my second form:
public partial class EquiposCargar : Form
{
// I saw some videos on youtube and this is how the pass some values,
// but it doesnt work with lists
public EquiposCargar(List<Grua>listaGrua)
{
InitializeComponent();
}
}
Could anyone please help me? im stuck.
The error says the parameter List<Grua>listaGrua is less accesible than the method EquiposCargar.EquiposCargar(List<Grua>)
just another question! how do i use the list on my second form? lol...
because it says the name listaGrua is not defined in the actual
content. It looks like i have to create a new variable and assign the
list parameter than i sent, right? but im doing it and its still not
working
That's correct, you need to create a variable in your second form to hold that reference. In the constructor, simply assign the passed in reference to your form's reference:
public partial class EquiposCargar : Form
{
private List<Grua> listaGrua;
public EquiposCargar(List<Grua> listaGrua)
{
InitializeComponent();
this.listaGrua = listaGrua;
}
}
Note the use of the this keyword. Now you should be able to use listaGrua from anywhere in your second form.
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();
I want to access the list box and add the item into it for my Custom control which is dynamically created on run time. I want to add the Item when I press the button place in the custom control, but it does not work. I have use the following code to work:
private void button1_Click(object sender, EventArgs e)
{
Form1 frm = new Form1();
frm.ABC = "HI";
}
the 'ABC' is the Public string on the form ie:
public string ABC
{
set { listBox1.Items.Add (value); }
}
the above string works fine when I use it form the Button on the form and it adds the value in the lsitbox but whent I use it form the custom control's button the text of the 'value' changes but it does not add the item in list box.I have also try it on tabel but does not help. I change the Modifires of the ListBox1 from Private to Public but it does not works. The above function works well in the form but cannot work from the custom control.
Thanks.
Expose an event ("ItemAdded" or whatever) in the child form that your main form can handle. Pass the data to any event subscribers through an EventArgs derived object. Now your mainform can update the UI as it please with no tight coupling between the two classes. One class should not know about the UI layout of another, it's a bad habit to get into (one that everyone seems to suggest when this question crops up).
What I think you should use is
this.ParentForm
So in your case it should be:
public string ABC
{
set { this.ParentForm.listBox1.Items.Add (value); }
}
The easiest way would be to pass the form down into your custom control as a parameter in the constructor that way you could access it from the custom control.
EX:
public class CustomControl
{
private Form1 _form;
public CustomControl(Form1 form)
{
_form = form;
}
private void button1_Click(object sender, EventArgs e)
{
_form.ABC = "HI";
}
}
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";
}