In my program on the WindowsForms I have two forms: parent and child. In the child form I've changed the value of the variable, which was declared in the independent class.
When I'm closing the child form, I need to display a new value of the variable in the label of parent form, but I can see only old value. How to update it?
Here how I'm displaying it in the constructor of the parent form:
label6.Text = indicators.Money + "$";
Edit1:
Can't understand, why it doesn't update. Code in the parent form:
private void button3_Click(object sender, EventArgs e)
{
Computer computer = new Computer();
computer.ShowDialog();
label6.Refresh();
}
Edit2
Here what I've done. I'm still experimenting with what you advised:
private void button3_Click(object sender, EventArgs e)
{
Computer computer = new Computer();
Code.Indicators indicators = new Code.Indicators();
if (computer.ShowDialog() == DialogResult.OK)
label6.Text = indicators.Money.ToString();
label6.Refresh();
}
Actually what I need:
Try the Control.Refresh Method like this:
label6.Refresh();
Edit Per Update
The real issue here is your approach. Here is a pretty simple way of returning a value from a child form which is what you want.
Add a property to your your child form which you can use to access the Money amount set from the parent form.
public partial class YourChildForm : Form
{
public string YourMoney { get; private set; }
// The rest of your form code
}
Sample usage:
var childForm = new YourChildForm();
childForm.ShowDialog();
label6.Text = childForm.YourMoney;
Since you are stating your are using ShowDialog you can read the value out of your Child form right after you return from the ShowDialog Method. As I stated in the comments I would just create a Public property to set and get the value of your variable.
Try something like this:
child.CurrentIndicator = indicators;
if(child.ShowDialog == DialogResult.OK)
indicators = child.CurrentIndicator;
label6.Text = indicators.Money;
create property in your child form something like this;
public Indicator CurrentIndicator {get; set;} //You can use automatic properties or have a backing variable
Related
This question already has answers here:
Passing Values from one Form to another Form in a Button click
(4 answers)
Closed 2 years ago.
Okay, I saw a couple of answers to similar questions but nothing was quite right, so I thought I would write down my own problem. I have a couple of Forms that are supposed to be connected.
private void btnAdd_Click(object sender, EventArgs e)
{
AuthorForm authorForm = new AuthorForm();
authorForm.Show();
}
This is the code from the Form2 that opens once I want to create a new list of Authors. With that, the third Form "AuthorForm" pops up and that's where I want to enter a name to add to a listBox that is in Form2. I don't know how to pass the string from the TextBox to the other form.
I'm sorry if this doesn't make much sense. I'm pretty bad at trying to explain what I need but if you have questions, I'll try to explain better.
Hi and welcome to StackOverflow. There are several ways to achieve this but I believe the easiest would be to use a property in your AuthorForm as follows:
// Inside AuthorForm create the following...
public string AuthorName { get; private set; }
Having done that, you can set this property either in text changed, or when the user clicks to commit the entered text, you then read this property from the Form2.
// This goes inside the text changed off your name text box.
this.AuthorName = AuthorTextBox.Text; // Assuming the name of the textox is AuthorTextBox
Inside Form2 you call read the property as follows.
private void btnAdd_Click(object sender, EventArgs e)
{
AuthorForm authorForm = new AuthorForm();
authorForm.ShowDialog();
// Read the entered text from the property
var userInput = authorForm.AuthorName;
}
You can proceed to make use of the text the user entered after this.
If i'm not mistaken you want to change Form2 instance after authorForm.Show(); statment
You can initial public variable for example name in Form2 and then send all the form2 instance to AuthorForm with constructor (use this keyword) , now you can change variable from form2 in authorForm
see :
AuthorForm authorForm = new AuthorForm();
authorForm.Show(this);
AuthorForm :
Form2 form2;
public AuthorForm(Form2 form2)
{
this.form2 = form2;
}
public void DoSomething()
{
form2.name = "test";
}
If I got it right, you want to get values from from AuthorForm.
You can do that by adding a property to the AuthorForm, like that:
public string AuthorName { get; set; }
And use authorForm.ShowDialog() so all the opened forms will freeze until you use the Close() method in the form you opened as a dialog. And then you can continue the form.
For example:
AuthorForm.cs:
public void BtnClose_Click(object sender, EventArgs e)
{
AuthorName = "rom_totach";
Close();
}
MainForm.cs:
public void BtnOpenAuthorForm(object sender, EventArgs e)
{
AuthorForm form = new AuthorForm();
form.ShowDialog();
MessageBox.Show(form.AuthorName);
}
I hope I helped!
I am struggling to pass data between two forms (all I want to do is have a textbox in Form1, and show that textbox value in textbox1, which is located in Form2). How would I go about this, using WPF? Have looked at quite a few solutions, but cannot seem to get any of them at all to work.
For the form in which I'm wanting to display the values (in tbd.Text), here is the code:
namespace test
{
/// <summary>
/// Interaction logic for OptionDisplayWindow.xaml
/// </summary>
public partial class OptionDisplayWindow : Window
{
public OptionDisplayWindow()
{
InitializeComponent();
tbd.Text = "k"; //want to change this value based on "s" in the other form
}
The form in which the text is transferred from (want to display the string):
public void Button1_Click(object sender, RoutedEventArgs e)
{
string s = "testText"
}
I have tried every single other answer on SO (spent the past 6 hours trying) and have had absolutely no luck.
EDIT 2: Using the method listed as the best answer here Send values from one form to another form I've come up with this code for Form1:
private void ttbtn_Click(object sender, RoutedEventArgs e)
{
using (Form2 form2 = new Form2())
{
tbd.Text = form2.TheValue;
}
}
And the code for Form2:
public string TheValue
{
get { return arrayTest.Text; }
}
However, I'm getting the error 'Form 2': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
The code that you put in the sample project (that you provided as a link in the comments) should be in your question. Given that it becomes much easier to understand what you're trying to do and to give you a workable solution.
I would suggest creating a "DataTransferObject" and pass that between each form.
public class Dto
{
public string Text;
}
The code in MainWindow would then look like this:
private void button1_Click(object sender, RoutedEventArgs e)
{
var dto = new Dto();
window2 win2 = new window2();
win2.Dto = dto;
win2.ShowDialog();
textBox1.Text = dto.Text;
}
And the code in window2 would look like this:
public Dto Dto;
private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
{
if (this.Dto != null)
{
this.Dto.Text = textBox2.Text;
}
}
That is one way - out of about a million - of transferring data between forms. An advantage of using a data transfer object is that it begins you on the road of separating your data from your UI, and that is generally a very good thing to do.
Another simple way to pass data between forms is using your application's settings.
Step 1: Create a setting, open the "Project" menu and pick "test Properties..."
this will take you to the settings page, create a setting name it however you want, I named mine "PassString" and make sure it's a string type and the Scope is set to user.
Step 2. Lets set the string setting to your textbox.text property, add these changes to the code:
private void button1_Click(object sender, RoutedEventArgs e)
{
Properties.Settings.Default.PassString = textBox1.Text;
window2 win2 = new window2();
win2.ShowDialog();
}
Step 3. Update the text on your second window Initialization Process.
public OptionDisplayWindow()
{
InitializeComponent();
tbd.Text = Properties.Settings.Default.PassString;
}
P.S. you may have to add a reference to reach your application settings.
using test.Properties;
I am working on a program that generates a PDF file. Before the final generation of the file, I want to give the user the option to edit a portion of the file (The title of the graph that is about to be created). I want this to show up in a new form when the user clicks a button to export the PDF. Here is an outline of what I am trying to do...
private void button4_Click(object sender, EventArgs e) // Test PDF Code!
{
Form2 NewPDF = new Form2(chart3.Titles[chart3.Titles.IndexOf("Header")].Text.ToString().Substring(0, chart3.Titles[chart3.Titles.IndexOf("Header")].Text.ToString().Length - 4));
NewPDF.Show();
if (NewPDF.Selected == true)
{
// Create PDF, open save file dialog, etc
}
}
And here is the Form that is being opened by this button click...
public partial class Form2 : Form
{
public bool Selected
{
get;
set;
}
public String GraphName
{
get;
set;
}
public Form2(String FileName)
{
InitializeComponent();
textBox1.Text = FileName;
GraphName = FileName;
Selected = false;
}
public void button1_Click(object sender, EventArgs e)
{
GraphName = textBox1.Text;
this.Selected = true; // After the button is selected I want the code written above to continue execution, however it does not!
}
}
As of now, when I click on the button in Form2, nothing happens, there is something about the communication between the two Forms that I am not understanding!
You should change your Form2.GraphName like below
public String GraphName
{
get { return textBox1.Text }
}
then change your new Form2 creation like below, test it since I haven't run this through VS, but should work :)
private void button4_Click(object sender, EventArgs e) // Test PDF Code!
{
// why on earth were you doing .Text.ToString()? it's already string...
Form2 NewPDF = new Form2(chart3.Titles[chart3.Titles.IndexOf("Header")].Text.Substring(0, chart3.Titles[chart3.Titles.IndexOf("Header")].Text.Length - 4));
// show as a dialog form, so it will wait for it to exit, and set this form as parent
NewPDF.ShowDialog(this);
if (NewPDF.Selected == true)
{
// get the name from the other form
string fileName = NewPDF.GraphName;
// Create PDF, open save file dialog, etc
}
}
The answer to your problem is quite simple.
NewPDF.Show();
Show() does not pause execution of the calling form. Therefore, the check underneath that that verifies the Selected property if true will never execute properly, since that check is reached and verified just as the form starts appearing. ShowDialog() does pause execution and waits for the called form to close.
That aside; I would recommend one of two other ways to communicate between forms;
Use a global variable. Declare a variable holding the graph's name somewhere in a public module. Call the dialog that asks the user to input a name with ShowDialog(), since that pauses execution of the calling form until the called form returns a result.
if(Form.ShowDialog() == DialogResult.OK) {
// Save pdf, using title in global variable
}
Make sure to set the DialogResult in the called form before Close()-ing it.
Pass an instance variable of the calling form to the called name-input form to the constructor and save it. That way, if you expose the graph name property as a public property, you should be able to access it from the called form in the code that closes the form, which is your:
public void button1_Click(object sender, EventArgs e)
{
callingFormInstance.GraphNameProperty = textBox1.Text;
Close();
}
Hope that helps. Cheers!
What im trying to do:
Search products by BarCode on Form1 form;
if it cannot be found:
1. Open Inventory form
2. Search product by name or description
3. On ListView click on the found product copy its BarCode and paste it to the Form1 barcode textbox.
All that is done corectly. The problem is that every time I add product from Inventory form a new Form1 is opened.
The values are not processed in the same Form1, so assume I sell 4 products:
2 of them are added through Form1 barcode search
2 of them are added through Inventory search form
In the end I get 3 opened Form1 forms, one with 2 products and two forms with single product (added through Inventory form). I need them to be all in one.
Thanks
//-------------------------Form1--------------------------------------------
private void btnInventory_Click(object sender, EventArgs e)
{
Inventory Inventory = new Inventory();
Inventory.Show();
}
private string _theValue;
public string TheValue
{
get
{
return _theValue;
}
set
{
_theValue = value;
txtItems.Text = value;
}
}
//-----------------------------Inventory---------------------------------
private void ShowForm1()
{
string value = label9.Text;
Form1 newForm = new Form1();
newForm.TheValue = value;
this.Close();
newForm.ShowDialog();
}
private void lvList_Click(object sender, EventArgs e)
{
label9.Text = lvList.SelectedItems[0].SubItems[0].Text;
this.ShowForm1();
}
Im sorry for the delay, i had to wait 8h before posting again
Thanks for ur reply.
I just tried that
Form1
private void btnInventory_Click(object sender, EventArgs e)
{
Inventory _inv = new Inventory();
if (DialogResult.OK == _inv.ShowDialog())
{
txtItems.Text = _inv.fugi;
}
}
and in Inventory Form
private string test;
public string fugi
{
get { return test; }
set { test = label9.Text; }
}
private void lvList_Click(object sender, EventArgs e)
{
label9.Text = lvList.SelectedItems[0].SubItems[0].Text;
this.DialogResult = DialogResult.OK;
this.Close();
}
txtItems.Text does not get the value of test from inventory form
Its opening a new dialog because you tell it to in ShowForm1, Personally I would change your btnInventory click as follows
private void btnInventory_Click(object sender, EventArgs e)
{
Inventory _inv = new Inventory();
if(DialogResult.OK == Inventory.ShowDialog())
{
valueIWantToSet = _inv.Accessor;
}
}
Accessor you will need to make yourself similar to
public TypeOfVar Accessor
{
get{return m_privateVariableThatIWillMakeAndSetToMyBarcode;}
}
Edit:
Once you have gotten the value of your barcode you need to set DialogResult as Follows
this.DialogResult = DialogResult.OK;
and then set the variable you wish to access to the barcode before closing your form
Edit2:
Your ShowForm1 will end up similar to this (May want to rename this method!)
{
this.DialogResult = DialogResult.OK;
m_myVar = SelectedItem..;
this.Close;
}
UPDATE ANSWER
You are still having problems as you haven't used the set property correctly, your get is fine as it is. There is a keyword in c# called value that should be used for setters. this value will take the value of whatever is on the right hand side of an = sign.. you can think of it like this...
fugi = label9.Text
In the above line, fugi is using your properties getter in order to get the value that needs to be set to label9.Text. The = sign says that you intend to use the setter for this property and set the value of value to label9.Text.
Properties with a getter and setter are used so you do not have to provide access to the underlying variable to somewhere you would not like to and then can have the option to just set or get this variable as needed.
This means that your problem persists have you have yet to set the value of test, it is still the default string value.
So you have a couple of ways to solve your problem.
The first way is just to provide a getter for label9.Text and remove the need for your private variable.
public string Fugi //Properties should really start with capital letter
{
get{return label9.Text;}
}
The second is to set the value of test before you call your getter in btnInventoryClick and remove the setter method
private void lvList_Click(object sender, EventArgs e)
{
test = label9.Text;
and the third ist to set test as shown in method 2 but also change the set method of Fugi to the following to allow this test variable to be set elsewhere.
set{text = value;}
I want to get some data to fill a listview control, but this data it's determined in other form. This is what I code in form1 (Nuevo_Credito):
private void combo_cliente_SelectionChangeCommitted(object sender, EventArgs e)
{
Credito_Grupo ventana = new Credito_Grupo(combo_cliente.SelectedItem);
ventana.ShowDialog();
}
public void AgregaIntegrantes(string id, string nombre, string monto)
{
ListViewItem elem = new ListViewItem(id);
elem.SubItems.Add(nombre);
elem.SubItems.Add(monto);
listView_integrantes.Items.Add(elem);
}
I'm invoking form2 (Credito_grupo) as show dialog window, then I want to retrieve some values and pass them to Form1 using the public method "AgregaIntegrantes". So in form2 I did the following:
public Credito_Grupo(dynamic item)
{
this.id = item.IDCliente;
this.nombre = item.NomComp;
InitializeComponent();
}
private void Credito_Grupo_Load(object sender, EventArgs e)
{
text_nombre.Text = this.nombre;
}
private void button_AgregaCliente_Click(object sender, EventArgs e)
{
Nuevo_Credito obj = new Nuevo_Credito();
obj.AgregaIntegrantes(id.ToString(), nombre, text_monto.Text);
this.Close();
}
When the event button_AgregaCliente_click is triggered I need to add the data to listview in form1 using the method described above, but none data is added. I found a solution using delegates here 3077677, is there an approach using objects?
You have an error in button_AgregaCliente_Click method (the last one in the listing). You create a new Nuevo_Credito form there, and pass the data to listview. It looks OK. But this newly created Nuevo_Credito form does exist only in the local variable, so then you throw it away without displaying it when button_AgregaCliente_Click finishes.
I think you need to delete this line: Nuevo_Credito obj = new Nuevo_Credito();
You need to get your real Nuevo_Credito form, not create a new one here.
You can send this from your Nuevo_Credito to the constructor of the Credito_Grupo form. Then you can use it to call back to the original Nuevo_Credito. This approach is based only on objects, and not delegates. As you wanted. :-)