public variables using in the second form - c#

I have a "simple" problem with assign variables from FORM1 (in my code Form1) and using those variables in FORM2 (in my code frLeczenie). So I started to create a public string variables:
public string wynikImie;
public string wynikUmaszczenie;
public string wynikDataUrodzenia;
public string wynikPlec;
public string wynikZnakiSzczegolne;
public string wynikCzyWykastrowane;
To those variables I'll assign data from SQL Database:
private void dgZwierze_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string zapytanie = "SELECT IMIE_ZWIERZECIA, DATA_URODZENIA, PLEC, ZNAKI_SZCZEGOLNE, UMASZCZENIE, CZY_WYKASTROWANE FROM tbZwierze WHERE tbZwierze.IMIE_ZWIERZECIA = '" + wynikImie + "' AND tbZwierze.UMASZCZENIE = '" + wynikUmaszczenie + "'";
SqlCommand cmdZapytanie = new SqlCommand(zapytanie, cs);
cs.Open();
SqlDataReader reader = cmdZapytanie.ExecuteReader();
if (reader.Read())
{
wynikImie = reader.GetValue(0).ToString();
wynikDataUrodzenia = reader.GetValue(1).ToString();
wynikPlec = reader.GetValue(2).ToString();
wynikZnakiSzczegolne = reader.GetValue(3).ToString();
wynikUmaszczenie = reader.GetValue(4).ToString();
wynikCzyWykastrowane = reader.GetValue(5).ToString();
}
cs.Close();
}
To this moment all is great, but problem occurs when I opened the FORM2:
private void btnLeczenie_Click(object sender, EventArgs e)
{
frLeczenie leczenie = new frLeczenie();
leczenie.ShowDialog();
}
Suddenly my all data assigned to public string variables is missing, and I can't using their in the FORM 2:
private void frLeczenie_Load(object sender, EventArgs e)
{
Form1 formaglowna = new Form1();
textBox1.Text = formaglowna.wynikImie;
textBox2.Text = formaglowna.wynikDataUrodzenia;
textBox3.Text = formaglowna.wynikPlec;
textBox4.Text = formaglowna.wynikZnakiSzczegolne;
textBox5.Text = formaglowna.wynikUmaszczenie;
textBox6.Text = formaglowna.wynikCzyWykastrowane;
}
What I'm doing wrong? Maybe I missing something? Could you take a look on this?
Regards,
Peter.

new Form1(); creates a new instance of your first form, but you want to use the already initialized form with it's variables instead. So you could pass the form instance via constructor to your second form and store it in a property:
in first form:
frLeczenie leczenie = new frLeczenie(this);
second form constructor:
public frLeczenie(Form1 formaglowna)
{
InitializeComponent();
this.Formaglowna = formaglowna;
// ...
}
public Form1 Formaglowna{ get; set; }
Now you access them via property:
textBox1.Text = Formaglowna.wynikImie;
// ...

Note that you set the values in an instance of the form in it's dgZwierze_CellContentClick method. However in form 2 you are creating a new Form1 that has never been shown or had that method called. So the values are empty.
Form1 formaglowna = new Form1();
textBox1.Text = formaglowna.wynikImie;
What you need is to pass the real form1 into form2 and not create a new form 1

When you create the new form1 in the last part of your code, it is a new blank instance of the class. Each instance of a class or form will have its own variable values. If you really need these variables to be available and shared on all objects of a given class, make them static.

Related

c# passing values through constructor but are not displayed in a textbox

i have passes some values though a constructor from one from to another. the values are successfully transferred in another form through constructor but when i display them in a textbox the values become null and the textbox remains empty. i am showing the code of the constructor for both forms.
starting form which opens another form
private void lbl_imgpass_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string img = img_name.Text;
Setimgpass st = new Setimgpass(img);
st.Show();
}
form1(from where the values are transferred to another form)
else
{
first = textBox2.Text;
second = textBox3.Text;
third = textBox4.Text;
Adduser add = new Adduser(x1low, x1up, x2low, x2up, x3low, x3up, y1low, y1up, y2low, y2up, y3low, y3up, first, second, third);
this.Hide();
}
second form(where the values are received)
public Adduser(string x1low, string x1up, string x2low, string x2up, string x3low, string x3up, string y1low, string y1up, string y2low, string y2up, string y3low, string y3up,string first, string second, string third)
{
InitializeComponent();
frst = first;
secnd = second;
thrd = third;
lowx1 = x1low;
upx1 = x1up;
lowx2 = x2low;
upx2 = x2up;
lowx3 = x3low;
upx3 = x3up;
lowy1 = y1low;
upy1 = y1up;
lowy2 = y2low;
upy2 = y2up;
lowy3 = y3low;
upy3 = y3up;
txt_imgpass.Text = frst + " " + secnd + " " + thrd;
}
txt_imgpass is the textbox in which i want values.
In the first form the values are passed to the object "add" that you created .
You can simply use static variables to pass data from one form to another .
EDIT
You might as well want to try something like this instead of static variables
Form 1 :
assuming this is the button you click on to show the second form
private void button1_Click(object sender, EventArgs e)
{
Form2 form = new Form2(textBox1.Text);
form.Show();
}
in Form 2 you can do something like this
public Form2(string text)
{
InitializeComponent();
label1.Text = text;
}

Can't add ListViewItem in function

I wrote a code that is build from 2 forms,
the main form - (Form1) that gets 3 strings from the sub form (AddTask)
In the main form:
public partial class Form1 : Form
{
int count = 0;
string taskName2, DateTime2, More2;
public Form1(string taskName1, string DateTime1, string More1, bool startworking)
{
InitializeComponent();
taskName2 = taskName1;
DateTime2 = DateTime1;
More2 = More1;
if(startworking)
{
StartWorking();
}
}
You can see I create 3 string to global use, Form1 gets 3 strings and 1 boolean variable. When the boolean is true the function StartWorking start.
In the sub form I have a button and 3 text boxes. The button has a click event:
string taskName1 = textBox1.Text;
string DateTime1 = textBox2.Text;
string More1 = textBox3.Text;
Form celender = new Form1(taskName1, DateTime1, More1, true);
this.Close();
So when I press the button on the sub form the boolean is set to true and the StartWorking function starts.
Up to here all is alright.
The function StartWorking:
public void StartWorking()
{
MessageBox.Show(taskName2 + " " + DateTime2 + " " + More2);
ListViewItem lvi = new ListViewItem(taskName2);
lvi.SubItems.Add(DateTime2);
lvi.SubItems.Add(More2);
listView1.Items.Add(lvi);
}
Now in the function the MessageBox works and shows the strings, but when I see the listview1 nothing changes. Why doesn't it create anything?
You didn't show Form1 after instantiating it. Show the Form1 with Show() method celender.Show(); and also change your code like this:
Hide();
string taskName1 = textBox1.Text;
string DateTime1 = textBox2.Text;
string More1 = textBox3.Text;
Form1 celender = new Form1(taskName1,DateTime1,More1,true);
celender.Show();
celender.Closed += (s, args) => this.Close();

How do I pass variables stored in Properties into another windows form?

So I need to be able to pass a property(name) into another windows form.
In the first form, the user is prompted to key in their name, while in the second one, their name is shown.
My problem is that although the value keyed in in the first form is saved (I have a Message box to show me) when the new form runs, the value of the property is reset to the placeholder name from the constructor class. Here are the codes(Form1 being the second form)
Both of them have initialised the reference to the contructor class at the start.
else if (select > 0 || txtName.Text != "")
{
p.Name = txtName.Text; // Save Name as property
MessageBox.Show("" + p.Name);
this.Hide();
Form1 form = new Form1();
form.ShowDialog();
}
For Form1:
private void Form1_Load(object sender, EventArgs e)
{
setName();
MessageBox.Show("" + p.Name);
timer1.Start();
label3.Text = "Player: " + p.Name;
}
Create a property in Form1 to accept the name:
public class Form1 : Form
{
//other stuff
public string Name {get;set;}
}
Then set that property when creating the form:
else if (select > 0 || txtName.Text != "")
{
this.Hide();
Form1 form = new Form1();
form.Name = txtName.Text;
form.ShowDialog();
}

Sharing data across forms with C# [duplicate]

This question already has answers here:
C# - Winforms - Global Variables
(8 answers)
Closed 9 years ago.
I have been trying, without success, to share a variable between multiple forms. I am very new to c# and so have been failing miserably despite reading a couple of things about it.. Below is the programs code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;
using System.Data.OleDb;
namespace login
{
public partial class LoginScreen : Form
{
public LoginScreen()
{
InitializeComponent();
}
// Variables
int count = 0;
public static System.Data.OleDb.OleDbConnection con =
new System.Data.OleDb.OleDbConnection();//database connection
string dbProvider;
string dbSource;
OleDbDataAdapter da; // create database adapter 'da'
// CREATE DATASET VARIABLE ds1 TO HOLD THE DATABASE
public static DataSet ds1 = new DataSet();
string accountNo;
string sql;
string password;
int rownum = 0;
bool valid = false;
private void btnLogin_Click(object sender, EventArgs e)
{
accountNo = txtBoxAccntNo.Text;
valid = validate(); //uses validate() method to check validity
if (valid == true && accountNo == "11111111")
{
ManagerScreen Manager = new ManagerScreen();
this.Hide();
Manager.Show();
}
else if (valid == true)
{
s customer = new s();
this.Hide();
customer.Show();
}
else
{
if (count == 2)
{
this.Close();
}
count += 1;
txtBoxAccntNo.Clear();
txtBoxPinNo.Clear();
}
}
private void txtBoxAccntNo_TextChanged(object sender, EventArgs e)
{
}
private void LoginScreen_Load(object sender, EventArgs e)
{
// open database connection and load contents
// database connection
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"; // this is the database provider
dbSource = "Data Source = 'C:\\Bank.accdb'"; // navigation path
con.ConnectionString = dbProvider + dbSource;
}
private void btnExit_Click(object sender, EventArgs e)
{
// If button exit selected hide this form and open the welcome screen
WelcomeForm Welcome = new WelcomeForm();
this.Hide();
Welcome.Show();
}
// IsValid method checks that pass and login are valid
private bool validate()
{
ds1 = new DataSet();
con.Open();
// Validate Account number
sql = "SELECT * FROM tblCustomers WHERE ((tblCustomers.AccountNo) = '" + txtBoxAccntNo.Text + "')";
da = new OleDbDataAdapter(sql, con);
rownum = da.Fill(ds1, "tblCustomers");
con.Close();
if (rownum != 1)
{
MessageBox.Show("Not a valid Account number! - Try Again ");
return false;
}
else
{
// validate the pin
password = ds1.Tables["tblCustomers"].Rows[0][4].ToString();
if (password == txtBoxPinNo.Text)
{
MessageBox.Show("valid");
return true;
}
else
{
MessageBox.Show("Not a valid password - please try again ");
return false;
}
}
}
}
}
I want to share the variable accountNo with all other forms. Please advise, as I really need to get on with this. Thank you for any help.
You can make that accountNo property as static or either you can have some getter method to access that too.
If you set accountNo as static you can access it by just calling
ClassName.PropertyName
in your case
LoginScreen.accountNo will be the account number property.
Simple code sample
public partial class LoginScreen : Form
{
public LoginScreen()
{
InitializeComponent();
}
public static string accountNo;
}
public class AnotherClass
{
string accountNo = LoginScreen.accountNo;
}
The right way to go about this is to use the form to retrieve the information and then store it somewhere else to be accessed as you need it. Don't access it directly in the form from elsewhere - this will require you to keep the login form in scope for the whole application lifecycle. This probably isn't what you want.
In practice, this means creating something like a Global static class that everything has access to:
public static class Globals {
public static string AccountNumber {
get;
set;
}
}
From in your login form, after validating the login as correct, you would simply do:
Globals.AccountNumber = txtBoxAcctNo.Text;
Then, anywhere else you need the AccountNumber, you can access it as Globals.AccountNumber.
I can recommend one of three ways to achieve what you want:
Make accountNo a public static variable. Then, other forms can access it by LoginScreen.accountNo (it's better to have a property to control visibility). This is a good approach if you might have many active instances of LoginScreen and they all might update accountNo and you want any form which accesses this field to get the latest value.
Implement a singleton pattern for the entire form and have accountNo in it as a public variable. This is a good approach if you will only have one instance of the firm active at any time.
Have accountNo be static member in another class and have LoginScreen access it by UtilClass.accountNo. This is a good approach if other forms/classes might want to update the field and/or it's a field which shouldn't be associated with this form.

Write Textbox to TextFile C#

I'm trying to write information to a TextFile through TextBoxes (TextFile in this case is something like a database). It's working when I use File.AppendAllText in the Form, but I'm trying to make it happen through Methods.
I created a method called AddClient()
Client getClient = new Client();
public void AddClient()
{
string client = getClient.FirstName + "," + getClient.LastName + "\r\n";
File.AppendAllText(textFilePath, client);
}
And the Register button in the Form is called RegisterButton and contains :
ClientRepository getMethods = new ClientRepository();
Client getClient = new Client();
private void RegisterButton_Click(object sender, EventArgs e)
{
getClient.FirstName = FirstNameTextBox.Text;
getClient.LastName = LastNameTextBox.Text;
getMethods.AddClient();
}
FirstName and LastName ofc are properties of public class Client
After the button click, they both get null values.
Help please ?
You don't pass the instance of the Client class that has the firstName and lastName correctly set from the input textboxes to the AddClient method, instead you create a new instance of a Client class inside the ClientRepository class, and, of course, this new instance has nothing in its properties.
Change your code to pass the instance of Client created in your form
in ClientRepository class
public void AddClient(Client clientToAdd)
{
string client = clientToAdd.FirstName + "," + clientToAdd.LastName + "\r\n";
File.AppendAllText(textFilePath, client);
}
in your form code
ClientRepository getMethods = new ClientRepository();
Client clientToAdd = new Client();
....
private void RegisterButton_Click(object sender, EventArgs e)
{
clientToAdd.FirstName = FirstNameTextBox.Text;
clientToAdd.LastName = LastNameTextBox.Text;
getMethods.AddClient(clientToAdd);
}

Categories