0

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.

Tass
  • 1,238
  • 11
  • 21
ptw
  • 23
  • 5

3 Answers3

1

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;
}
Ash Burlaczenko
  • 24,778
  • 15
  • 68
  • 99
Roshana
  • 428
  • 3
  • 15
  • If you need to take the value from the LoginScreen form and make it available for rest of the forms First - on after the text changed you can set the value accountNo = textBox1.Text; and then you can access it. – Roshana Mar 05 '13 at 11:42
1

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.

Tass
  • 1,238
  • 11
  • 21
  • 1
    You need to read up on [Properties](http://msdn.microsoft.com/en-gb/library/x9fsa0sw(v=vs.80).aspx) – DGibbs Mar 05 '13 at 11:43
  • The `get` and `set` above define AccountNumber as a property. You can think of it as a variable, only better. Have a look at http://stackoverflow.com/questions/4142867/what-is-difference-between-property-and-variable-in-c-sharp – Tass Mar 05 '13 at 11:46
  • My first code block is all you need in the globals.cs file - within a namespace block. The second block is the only extra code you need in your login form. You can set and access `Globals.AccountNumber` from anywhere in your application. – Tass Mar 05 '13 at 20:02
  • This answer would be more useful if it included legal C# code. In particular, the `AccountNumber` property is required to be declared as `static` itself, both because otherwise it's not accessible via the type name, and because the class itself is declared as `static` (i.e. non-static properties aren't even allowed). – Peter Duniho Oct 28 '15 at 20:33
0

I can recommend one of three ways to achieve what you want:

  1. 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.
  2. 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.
  3. 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.
ytoledano
  • 3,003
  • 2
  • 24
  • 39