I'm creating a program that involves a user logging in on Form1 in order to access Form2. When at Form2, a Label at the top needs to display the user's first name and job position. So, I'll have to pass the name and position variables from Form1 to Form2 in order to display it. Unfortunately, when I try to do this, it won't display.
Currently, the program is set to check the database for the entered login credentials, while an OleDBDataReader finds the name and position associated with those credentials. I've tried declaring a public static string in order to pass the variable along to Form2, but it only returns a null value.
On Form 1, above the Button_Click method:
private string _name;
public string name
{
get
{ return _name; }
set
{ _name = value; }
}
private string _position;
public string position
{
get
{ return _position; }
set
{ _position = value; }
}
On Form1 beneath Button_Click method:
try
{
if (textBox1.Text == string.Empty || textBox2.Text == string.Empty)
{
MessageBox.Show("Invalid! Please enter a valid Username and/or Password.");
}
cmd = new OleDbCommand("SELECT * FROM Staff Where Username='" + textBox1.Text + "' AND Password='" + textBox2.Text + "'", sql);
if (sql.State == ConnectionState.Closed)
{
sql.Open();
i = (int)cmd.ExecuteScalar();
}
using (OleDbDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
_name = (read["FirstName"].ToString());
_position = (read["Position"].ToString());
}
}
sql.Close();
if (i > 0)
{
MainHub enter = new MainHub();
this.Hide();
enter.Show();
}
else
{
MessageBox.Show("Invalid! Please enter the correct username or password.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Finally, On Form2:
Form1 f=new Form1();
string name = f.name;
string position = f.position;
Label2.Text = "Welcome! Now logged in as User " + name +" ("+ position + ").";
I'd like Label2 to read "Welcome! Now logged in as [insert name] ([insert position])." Instead it just leaves those name and position slots empty.