Get variable from public class for two forms - c#

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 ...

Related

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

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!");
}
}
}

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.

Modify value in a class then use it in another form

I have form1, form2 and a class. i want to use form2 to modify a variable in a class then read that variable in form1.
The thing is that the variable doesn't change when i try to read it from form1, nor it stays after i open form2 again.
This is my code:
Form1
namespace app1 {
public partial class Form1 : Form {
Class1 md = new Class1();
public Form1() {
InitializeComponent();
}
private void loginToolStripMenuItem_Click(object sender, EventArgs e) {
Login login = new Login();
login.MdiParent = this;
login.enbctrs += new ShowFrm(enablecrts);
login.disctrs += new ShowFrm(disablecrts);
login.Show();
}
private void Form1_Load(object sender, EventArgs e) {
if (md.user == null) {
disablecrts();
stat_usr.Text = "No active user";
} else {
stat_usr.Text = md.user.ToString();
}
}
void disablecrts() {
stat_usr.Text = "No active user";
}
void enablecrts() {
stat_usr.Text = md.user;
}
}}
Form2
namespace app1.Forms {
public delegate void ShowFrm();
public partial class Login : Form {
public event ShowFrm enbctrs;
public event ShowFrm disctrs;
int ing_counter = 0;
Class1 md = new Class1();
public Login() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
string u = "user";
string p = "pass";
if(Txt_user.Text == u && Txt_pass.Text == p) {
string msg = "Welcome: " + u + "";
MessageBox.Show(msg, "", MessageBoxButtons.OK);
md.changeusr(u);
active_user.Text = md.user.ToString();
enbctrs();
}
private void Login_Load(object sender, EventArgs e) {
if (md.user == null) {
active_user.Text = "No active user";
} else {
active_user.Text = md.user.ToString();
}
}
}}
Class1
namespace app1.Modules {
class Class1 {
public string user;
public void changeusr(string u) {
user = u;
return;
}
}}
There are a number of things that could be improved in your code. But the main issue is that when you create the Login class in your loginToolStripMenuItem_Click() method, that new Login instance is also creating a new instance of Class1 and using that instead of the instance that your Form1 knows about. So when Login changes the user value, it's changing it in a location that Form1 doesn't know anything about.
The simplest fix IMHO is to have Form1 just pass the Class1 reference to Login for it to use, instead of having Login create its own instance. For example:
public partial class Login : Form {
// ...
readonly Class1 md;
public Login(Class1 md) {
InitializeComponent();
this.md = md;
}
// ...
}
And in Form1:
private void loginToolStripMenuItem_Click(object sender, EventArgs e) {
Login login = new Login(md);
login.MdiParent = this;
login.enbctrs += new ShowFrm(enablecrts);
login.disctrs += new ShowFrm(disablecrts);
login.Show();
}
Then when Login changes the user and raises the event, it will have changed the value in the same instance Form1 is using, and so Form1 will get the desired value in its own code.
public static class global{
public static int myInt = 0;
}
public class Form1{
global.myInt = 10;
}
public class Form2{
Console.WriteLine(global.myInt.ToString());
}

Passing a AVLTree between forms

There is another question that is very similar to mine however after reading it i still cannot get it to work.
I have two forms , MainForm and SecondForm and a few other classes, i need an instance of my AVLtree and be able to access it through my other forms.
This is what ive done so far
MainForm
public partial class MainForm : Form
{
AddArtist secondForm = new AddArtist();
public static AVLTree<Artist> treeAVL { get; set; }
public MainForm()
{
InitializeComponent();
}
private void butAdd_Click(object sender, EventArgs e)
{
secondForm.Show();
}
private void MainForm_Load(object sender, EventArgs e)
{
}
}
}
SecondForm
public partial class AddArtist : Form
{
String Name1 = "No Name";
int Members = 0;
public AVLTreetreeAVL = new AVLTree();
public AddArtist()
{
InitializeComponent();
treeAVL = MainForm.treeAVL;
}
private void MainForm_Load(object sender, EventArgs e)
{
}
private void butAdd_Click(object sender, EventArgs e)
{
Name1 = tBName.Text;
Members = (Convert.ToInt32(tBMem.Text));
Artist newArtist = new Artist(Name1,Members);
try
{
treeAVL.InsertItem(newArtist);
}
catch (Exception )
{
MessageBox.Show("No Data Entered", "Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
}
tBName.Text = "";
tBMem.Text = " ";
}
}
}
Any help would be greatly appreciated pointing out where im going wrong or how to solve it.
It now compiles however it gives an error of Object reference not set to an instance of an object. i hope ive gone about coding this is the right way.
What is the access modifier of AVLTree class? Check if it is private or internal, since your code needs it to be public.
Set public on your parametrized type
public class Artist
{
..
}

setter c# shows error make sure you do not have an infinite loop or infinite recursion

this is the topic connection for get user input in form 2 and display data in form 1.
This is my code in form2.
public string UserText
{
get
{
return this.textBox1.Text;
}
set
{
this.UserText = value;
}
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("Please enter keyword to search");
}
else
{
//anta data input to form1.
UserText = textBox1.Text;
}
and this is my code in form1
private void Form1_Load(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.ShowDialog();
string text = form2.UserText;
}
i want when we click on button search, it will automatically display the data when we load the form1.
when i run, it says at the setter:
make sure you do not have an infinite loop or infinite recursion.
why it says that?what did i do wrong?
i also had tried did.
public string UserText
{
get
{
return this.UserText;
}
set
{
this.UserText = value;
}
}
but it appears the same.
====EDIT====
now im trying to use this:
public string UserText
{
get
{
return this.textBox1.Text;
}
set
{
this.textBox1.Text = value;
}
}
also i tried this:
public string UserText { get; set;}
it does not show the error however, it also does not load the form1. the operation just stops there. is there anything i have done it wrong?
The code in your setter for the UserText property: this.UserText = value; calls itself. Based on the getter, I think you should make the setter be like this:
set
{
this.textBox1.Text = value;
}
if you are using C# 4
public string UserText {get;set;}
you have to put the Form2 in the Form1 Constructor
public Form1()
{
this.InitializeComponent();
Form2 form2 = new Form2();
form2.ShowDialog();
string text = form2.UserText;
}
this will happend before the Form1 is shown

Categories

Resources