How can I pass 2 variables from one form to another? - c#

I have 2 forms: Game and newPlayer. When you press a button in Game, it opens the dialog of the newPlayer form, where someone would type his/her name and choose a Color in a comboBox between red, green, blue or yellow. I save that information in 2 variables: name (string) and color (int - being the index of the comboBox). I want to pass those 2 variables to the form Game.
I've tried unifying them in just one string and pass just one variabe to Game form, without success.
public partial class Game : Form
{
static int nPlayers = 4;
static List<Player> players = new List<Player>();
public string name = "";
private void button3_Click(object sender, EventArgs e)
{
using (newPlayer np = new newPlayer())
{
if (np.ShowDialog() == DialogResult.OK)
{
this.name = np.TheValue;
}
}
MessageBox.Show("Welcome " + name + "!");
}
and then:
public partial class newPlayer : Form
{
public string name = "";
public string TheValue
{
get { return this.name; }
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
if (comboBox1.SelectedIndex > -1)
{
this.name = textBox1.Text + comboBox1.SelectedIndex.ToString();
MessageBox.Show(newPlayer.name);
this.Close();
} else
{
MessageBox.Show("Write your name and choose a color!");
}
} else
{
MessageBox.Show("Write your name and choose a color!");
}
}
On the MessageBox of newPlayer it appears correctly like "Name1", for example. But on the MessageBox of Game, it appears empty. Can someone help, please?

You have forgotten to set the DialogResult when closing the form.
Try this:
this.DialogResult = DialogResult.OK;
this.Close();
If I were writing this code I might have done it more like this:
Game:
public partial class Game : Form
{
public Game()
{
InitializeComponent();
}
private string _playerName = "";
private void button3_Click(object sender, EventArgs e)
{
using (NewPlayer np = new NewPlayer())
{
if (np.ShowDialog() == DialogResult.OK)
{
_playerName = np.PlayerName;
MessageBox.Show($"Welcome {_playerName}!");
}
}
}
}
NewPlayer:
public partial class NewPlayer : Form
{
public NewPlayer()
{
InitializeComponent();
}
private string _playerName = "";
public string PlayerName
{
get { return _playerName; }
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && comboBox1.SelectedIndex > -1)
{
_playerName = $"{textBox1.Text}{comboBox1.SelectedIndex}";
MessageBox.Show(_playerName);
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
MessageBox.Show("Write your name and choose a color!");
}
}
}

Related

Passing values from form1 to form2 via button click to form2 [duplicate]

This question already has an answer here:
How to open new form, pass parameter and return parameter back
(1 answer)
Closed 4 years ago.
frmPlaceOrder is my form1. I need to pass the firstName, lastname and Address from this form to the second one which will do the other functions. I don't know how to do that.
namespace Lab1_OrderCake
{
public partial class frmPlaceOrder : Form
{
public static CustomerInformation customer;
public static Address address;
public frmPlaceOrder()
{
InitializeComponent();
customer = new CustomerInformation(txtFName.Text, txtLName.Text);
address = new Address(txtAddress.Text, txtCity.Text, txtPC.Text, txtProvince.Text);
}
private void btnPlaceOrder_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
if (txtFName.Text == "")
{
MessageBox.Show("Please enter first name", "Data Missing");
txtFName.Focus();
return;
}
if (txtLName.Text == "")
{
MessageBox.Show("Please enter Last name", "Data Missing");
txtLName.Focus();
return;
}
else
{
frmCakeOrder newCust = new frmCakeOrder();
this.Hide();
newCust.ShowDialog();
this.Close();
}
}
}
}
The second form; after the first one has been filled out needs to take the values from form1 and display it with the other values(frmCakeOrder values) in the second form. It needs to be seen in the View and Order events when i click it.
here is the Second form:
namespace Lab1_OrderCake
{
public partial class frmCakeOrder : Form
{
Order cakeOrder;
public List<Cake> cakeList;
public frmCakeOrder()
{
InitializeComponent();
cmbTraditionalCake.SelectedIndex = 0;
cakeOrder = new Order();
gbCustomCake.Visible = false;
this.Size = new Size(700,360);
cakeList = new List<Cake>();
}
private void bttnOrder_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
dlgMsg = MessageBox.Show(cakeOrder.ToString(), "Confirm Order", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dlgMsg == DialogResult.Yes)
{
MessageBox.Show(cakeOrder.PrintConfirmation());
}
else
{
MessageBox.Show ("The order has not been placed");
}
bttnReset.Focus();
cakeOrder.ClearCart();
}
private void radCustom_CheckedChanged(object sender, EventArgs e)
{
if (radCustom.Checked)
{
cmbTraditionalCake.Enabled = false;
gbCustomCake.Visible = true;
}
else
{
cmbTraditionalCake.Enabled = true;
gbCustomCake.Visible = false;
}
}
private void btnView_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
cakeOrder.NumOfCakes=1;
dlgMsg = MessageBox.Show(cakeOrder.ToString(), "Your order: ", MessageBoxButtons.YesNo , MessageBoxIcon.Information);
if (dlgMsg == DialogResult.No)
{
cakeOrder.ClearCart();
MessageBox.Show("Please enter and confirm your order!");
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (radCustom.Checked)
{
string flavour, occasion;
flavour = occasion = "";
int layers;
//for flavor
if (radBanana.Checked)
flavour = "Banana";
else if (radChocolate.Checked)
flavour = "Chocolate";
else if (radVanilla.Checked)
flavour = "Vanilla";
if (radTier2.Checked)
layers = 2;
else if (radTier3.Checked)
layers = 3;
else
layers = 1;
if (radGraduation.Checked)
occasion = radGraduation.Text.TrimStart(new char[] { '&' });
else if (radWedding.Checked)
occasion = radWedding.Text.TrimStart(new char[] { '&' });
else occasion = radAnniversary.Text.TrimStart(new char[] { '&' });
cakeOrder.AddCake(new Custom(flavour, occasion, layers));
}
else
{
cakeOrder.AddCake(new Traditional(cmbTraditionalCake.SelectedItem.ToString()));
}
cakeList.Add(cakeOrder);
}
}
}
There are many ways to do this. Try it this way.
private void btnPlaceOrder_Click(object sender, EventArgs e) {
string fname = textBox1.Text;
frmCakeOrder frm = new frmCakeOrder(textBox1.Text);
frm.Show();
}
And in frmCakeOrder,
public frmCakeOrder(string fname) {
InitializeComponent();
textBox1.Text = fname;
}
You can pass the data in the constructor:
public class Form1: from{
//constructor
public void Form1(){
}
public void button_click(){
//Get the data
var firstName = textFirstName.text;
var secondName= textSecondName.text;
var address= textAddress.text;
//Pass the data on the constructor of Form2
Form2 f2 = new Form2(firstName,secondName, address);
f2.show();
}
}
public class Form2: Form{
//constructor with data or parameters
public void Form2(string firstName, string lastName, string Address){
//do dosomething with the data
txtFirstName.text = firstName;
}
}
*sorry if it has sintaxys errors.... but thats the idea.

Get variable from public class for two forms

I want to open a new form - AdminForm from my existing form. The new form asks for a password, which should be transfered to a variable in the MainForm.
For this I've created a class:
public class Decrypt
{
public static string AdminPass { get; set; }
}
I referenced the public class in the AdminForm and set a value in the AdminPass variable.
public Decrypt AdminPass { get; set; }
private void button1_Click(object sender, EventArgs e)
{
if (txtAdminPass.Text == "2017")
{
Decrypt.AdminPass = "yes";
this.Close();
}
else
{
MessageBox.Show("Incorrect. Try again.");
}
}
Finally, I'm trying to access the variable in my MainForm like this:
private void btnDecrypt_Click(object sender, EventArgs e)
{
using (AdminForm openForm = new AdminForm() { AdminPass = new Decrypt() })
{
if (openForm.ShowDialog() == DialogResult.OK)
{
label23.Text = Decrypt.AdminPass;
}
}
}
Edit: the variable to Decrypt.AdminPass;
However. The variable seems to be assigned only in the AdminForm. So if I do MessageBox.Show(Decrypt.AdminPass); in the AdminForm, the string 'Yes' gets printed. But in MainForm, the label23.Text remains the same.
Any clues where I'm getting it wrong?
I understand this is a basic question, but I'm quite new to C#.
if (txtAdminPass.Text == "2017")
{
Decrypt.AdminPass = "yes";
//this.Close();
DialogResult = DialogResult.OK; // !!!
}
else ...

C# - Windows Application - Saving List

I have made a simple TO-DOs program that gets input from a text box then place it in another text box. With tick boxes next to it,
this is all fine except i Cannot save the list eg. the item and if it's finished or not.
Please could anyone help me be able to save this list of items.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TO_DOs
{
public partial class Form1 : Form
{
private bool text1, text2, text3, text4, text5, text6, text7, text8;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (text1 == false)
{
textBox2.Text = textBox1.Text;
}
else if (text2 == false)
{
textBox3.Text = textBox1.Text;
}
else if (text3 == false)
{
textBox4.Text = textBox1.Text;
}
else if (text4 == false)
{
textBox5.Text = textBox1.Text;
}
else if (text5 == false)
{
textBox6.Text = textBox1.Text;
}
else if (text6 == false)
{
textBox7.Text = textBox1.Text;
}
else if (text7 == false)
{
textBox8.Text = textBox1.Text;
}
else if (text8 == false)
{
textBox9.Text = textBox1.Text;
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
text1 = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
text2 = true;
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
text3 = true;
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
text4 = true;
}
private void textBox6_TextChanged(object sender, EventArgs e)
{
text5 = true;
}
private void textBox7_TextChanged(object sender, EventArgs e)
{
text6 = true;
}
private void textBox8_TextChanged(object sender, EventArgs e)
{
text7 = true;
}
private void textBox9_TextChanged(object sender, EventArgs e)
{
text8 = true;
}
}
}
I would do it like this:
Create a class to store your values in:
public class ListEntry
{
public string Text { get; set; }
public bool Finished { get; set; }
}
Then I would create 2 Methods:
public List<ListEntry> UI_To_List(); //Create UI from your saved file
public void List_To_UI(List<ListEntry> entries); //Process your UI
Now it's your choice on how to store your list.
You could store it as JSON or XML.
A few recommendations:
I would create a UserControl for your TextBox + CheckBox
Display the 'List of UserControls' in a FlowLayoutPanel
=> then you can process the FlowLayoutPanel.Controls List.
This will make your List dynamically size to an 'unlimited' amount of items.
Short example:
Create a UserControl (Rightclick project for that):
Add these 2 methods to the code of your UserControl (F7 / rightclick => View Code):
public void SetText(string text)
{
//Set the Text of your TextBox in the UserControl:
textBox1.Text = text;
}
public void SetFinished(bool finished)
{
//Set the Checked of your CheckBox in the UserControl:
checkBox1.Checked = finished;
}
In your MainForm add an FlowLayoutPanel (from ToolBox).
Add your Data like this (using class from above):
/// <summary>
///
/// </summary>
/// <param name="entries">You will get them from loading your previously saved file</param>
public void CreateUI(List<ListEntry> entries)
{
foreach (ListEntry entry in entries)
{
//Create new instance of your UserControl
TaskView view = new TaskView();
view.SetFinished(entry.IsFinished);
view.SetText(entry.Text);
//Add that to your UI:
this.flowLayoutPanel1.Controls.Add(view);
}
}
The result will look like this:
I'm not sure what exactly it is that you want to save in a list... but here's just a tip when checking conditions, instead of using if (text1 == false), simply do if (!text1) as this means "is not true" because by default if (text1) will return true.
private void button1_Click(object sender, EventArgs e)
{
if (!text1)
{
textBox2.Text = textBox1.Text;
}
else if (!text2)
{
textBox3.Text = textBox1.Text;
}
// Left out the rest of the else ifs
}
You are casting textboxes wrong. For example when you change textBox4, you gave text3 true.
private void textBox4_TextChanged(object sender, EventArgs e)
{
text3 = true;
}
Then you cast
TextBox4.Text = TextBox1.Text;
It changes TextBox4.Text to TextBox1.Text.
You probably want to save TextBox4.Text here at TextBox1.Text so you sould change all if blocks like that. So you have to give only one "true" function for changed textBox sign and change if blocks
if(text(boolNum))
TextBox1.Text = TextBox(Number).Text;
Just swap them and try like that.
If you want to save another thing by another way. You have to be more spesific.
You can use a CheckedListbox to hold all tot actions.
You can then tick the itemsand for instance in the OK button you include a save action:
foreach(var item in MyCheckedListbox.CheckedItems)
{
Console,WriteLine(item.Text);
}
Lets see the answer from Felix D. He tells you exactly how to create a class and save the items into it. But now you only have a List that will be available as long as your software is running. You still need to save it somewhere on your desktop.
Lucky for you, you got a really simple pattern.
string; boolean
So how about you make it yourself simple? Just create a textfile and write your entries, as example in a csv marked with a ; for every information?
Example:
class Program
{
public class tmpClass
{
public string Text;
public bool tick;
}
public List<tmpClass> tmpList = new List<tmpClass>();
static void Main(string[] args)
{
//Stuff
}
public void WriteToFile()
{
string tmpTextFilePath = #"C:\User\Desktop\SaveText.txt";
using (StreamWriter tmpWriter = new StreamWriter(tmpTextFilePath))
{
string tmpTextToWrite = String.Empty;
for (int i = 0; i < tmpList.Count; i++)
{
tmpClass tmpEntry = tmpList[i];
tmpTextToWrite += tmpEntry.Text + ";" + tmpEntry.tick;
}
tmpWriter.WriteLine(tmpTextToWrite);
}
//Now we wrote a text file to you desktop with all Informations
}
public void ReadFromFile()
{
string tmpTextFilePath = #"C:\User\Desktop\SaveText.txt";
using (StreamReader tmpReader = new StreamReader(tmpTextFilePath))
{
string tmpText = tmpReader.ReadLine();
string tmpInput = String.Empty;
tmpClass tmpClass = new tmpClass();
int i = 0;
foreach (char item in tmpText)
{
if(item.Equals(";".ToCharArray()))
{
if (i == 0)
{
tmpClass.Text = tmpInput;
i = 1;
tmpInput = String.Empty;
}
else
{
if (tmpInput == "True")
tmpClass.tick = true;
else
tmpClass.tick = false;
i = 0;
tmpInput = String.Empty;
tmpList.Add(tmpClass);
}
}
tmpInput += item;
}
}
}
}
This should simply write a txt File to your desktop with your information and read one and save it to your list.

How to get value from one form to an other?

I made a form for deleting/removing products.
Now my question is how do I get the value from one form to the other so I can use this to update the amount of products or delete the products from a database?
I'm trying to get the value of tbAantal.Text, so I can use this in my other form to update the amount of products.
Or should I do it in a other way?
public partial class Bevestiging : Form
{
public Bevestiging()
{
InitializeComponent();
Aantal = 0;
}
public int Aantal { get; set; }
private void btnOk_Click(object sender, EventArgs e)
{
int aantal;
if (!int.TryParse(tbAantal.Text, out aantal))
{
MessageBox.Show("U kunt alleen numerieke waardes invullen.", "Fout");
return;
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void BtUp_Click(object sender, EventArgs e)
{
Aantal++;
tbAantal.Text = Aantal.ToString();
}
private void BtDown_Click(object sender, EventArgs e)
{
Aantal--;
tbAantal.Text = Aantal.ToString();
}
So I can use this to update it here:
private void gridGeregistreerd_ColumnButtonClick(object sender, ColumnActionEventArgs e)
{
var dialog = new Bevestiging();
if (DialogResult.OK != dialog.ShowDialog()) ;
}
You've already made the public property "Aantal" on your first form with the right get/set so to retrieve the value on your second form use this:
using (Bevestiging myForm = new Bevestiging())
{
DialogResult result = myForm.ShowDialog();
if (result != DialogResult.OK)
{
int returnedValue = myForm.Aantal;
}
}
In you form, you have already define a public property :
public partial class Bevestiging : Form
{
public int Aantal {
get; set;
}
}
Then in your callee form, you can access it :
private void gridGeregistreerd_ColumnButtonClick(object sender, ColumnActionEventArgs e)
{
var dialog = new Bevestiging();
if (DialogResult.OK != dialog.ShowDialog())
{
int aantal = dialog.Aantal;
/* Save it to database or whatever you want */
}
}

send TextBox Values from FormB to a datagridView in FormA

I have to send the value of 2 TextBoxes from FormB when I clic on the "validate buton" to the datagridView in FormA;this is what I try to code:
FormB:
namespace RibbonDemo.Fichier
{
public partial class NvFamillImmo : Form
{
public event BetweenFormEventHandler BetweenForm;
SqlDataAdapter dr;
DataSet ds = new DataSet();
string req;
public NvFamillImmo()
{
InitializeComponent();
affich();
}
private void button2_Click(object sender, EventArgs e) //the validate buton
{
if (BetweenForm != null)
BetweenForm(textBox1.Text, textBox2.Text);
}
private void fillByToolStripButton_Click(object sender, EventArgs e)
{
try
{
this.amortissementFiscalTableAdapter.FillBy(this.mainDataSet.amortissementFiscal);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
}
}
and this is FormA:
namespace RibbonDemo.Fichier
{
public delegate void BetweenFormEventHandler(string txtbox1value, string txtbox2value);
public partial class FammileImm : Form
{
private NvFamillImmo nvFamillImmo;
public FammileImm()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
NvFamillImmo frm2 = new NvFamillImmo();
frm2.BetweenForm += frm2_BetweenForm;
frm2.ShowDialog();
}
void frm2_BetweenForm(string txtbox1value, string txtbox2value)
{
//dataGridView1.Refresh();
String str1 = nvFamillImmo.textBox1.Text.ToString();
this.dataGridView1.Rows[0].Cells[0].Value = str1;
}
}
}
EDIT:I filled the method frm2_BetwwenForm but now I get a problem in reference
thanks for Help
No Need to create event for that. you can create properties in second form where you want to send value from existing form. for example if you have two forms FormA and FormB then FormB should contains properties like Value1 and Value2.
//FormB
public class FormB :Form
{
public string Value1{get; set;}
public string Value2{get; set;}
}
Now you can assign value into both properties from FormA.
//FormA
public void button1_click(object sender, EventArgs e)
{
FormB myForm = new FormB();
myForm.Value1 = textBox1.Text;
myForm.Value2 = textBox1.Text;
myForm.Show();
}
Then you can get both textboxes value into FormB. You can handle value into Form Load event
//FormB
public void FormB_Load(object sender, EventArgs e)
{
string fromTextBox1 = this.Value1;
string formTextBox2 = this.Value2;
}
If the FormB is already loaded and want to send value from FormA then create a method UpdateValues() and modify the properties to call that method.
//FormB
string _value1 = string.Empty;
public string Value1
{
get { return _value1; }
set {
_value1 = value;
UpdateValues();
}
}
string _value2 = string.Empty;
public string Value1
{
get { return _value2; }
set {
_value2 = value;
UpdateValues();
}
}
private void UpdateValues()
{
string fromTextBox1 = this.Value1;
string fromTextBox2 = this.Value2;
}
and Assign the values in FormB.Value1 and FormB.Value2 properties from FormA.
//FormA
FormB myForm = new FormB();
public void button1_click(object sender, EventArgs e)
{
if (myForm != null && myForm.IsDisposed == false)
{
myForm.Value1 = textBox1.Text;
myForm.Value2 = textBox1.Text;
}
}
When the value is updated from FormA then UpdateValues() method will be called.

Categories

Resources