简体   繁体   中英

Can't find how to pass a variable from one form to another c#

I can't seem to find any resources to specifically help me with my problem. I want to be able to pass my variable that I have retrieved from my table to another form so I can tell who has signed in.

I want to be able to pass the variable called signedin(string) or the variable x(int) to my form called AddStudentAccForm.cs depending if it is easier to pass an integer or string.

I'd be very grateful for any help anyone could provide! Thank you!

This is my code where I create the variable in my form called StartMenu.cs:

private void TeacherLoginButton_Click(object sender, EventArgs e)
    {



        string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
        SqlConnection connect = new SqlConnection(connectionString);
        connect.Open();



        SqlCommand command10 = new SqlCommand(@"SELECT [Username], [Password] FROM TeacherDetails WHERE ([Username]=@username  AND [Password]=@password);", connect);


        command10.Parameters.AddWithValue("@username", usernameTlogin.Text);
        command10.Parameters.AddWithValue("@password", passwordTlogin.Text);
        SqlDataReader reader;
        reader = command10.ExecuteReader();
        int count = 0;

            while (reader.Read())
            {
                count = count + 1;


            }
            if( count == 1)
            {
                MessageBox.Show("Usename and password is correct");

                this.Hide();
                TeacherDashboardForm TeacherDashboard = new TeacherDashboardForm();
                TeacherDashboard.Show();
            }
            else if (count > 1)
            {

                MessageBox.Show("BEEP BOOP ERROR");
            }
            else
            {

                MessageBox.Show("Username or password is incorrect");
            }
            connect.Close();
            connect.Open();
            SqlCommand command11 = new SqlCommand(@"SELECT [TeacherID] FROM TeacherDetails WHERE ( [Username]=@username AND [Password]= @password)", connect);
            command11.Parameters.AddWithValue("@username", usernameTlogin.Text);
            command11.Parameters.AddWithValue("@password", passwordTlogin.Text);

            reader = command11.ExecuteReader();
            int x = 0;
                while (reader.Read())
                {
                    x = reader.GetInt32(0);

                }

                String signedin;
                signedin = x.ToString();

                MessageBox.Show(signedin);
    }

You need to organize your code in classes/models which represent your software architecture.

Like you have to create class:

    public static class Sql
        {

     public static AuthenticationModel Login(string userName, string password)
            {
                DataTable dt = GetResponseTable("Select UserID,Password from User where userName=" + userName);
                AuthenticationModel details = new AuthenticationModel{LoginStatus = "Failed"};
                if(dt..Rows.Count > 0 )
                  details = new AuthenticationModel{ LoginStatus = "Success", UserName = userName, UserId = dt["UserID"].toString();

                return details;
            }

private static DataTable GetResponseTable(string StoredProcedureName)
        {
            SqlConnection Con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);

            DataTable dt = new DataTable();
            Con.Open();
            SqlCommand cmd = new SqlCommand(StoredProcedureName, Con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            Con.Close();
            return dt;
        }

    }

And use this above model across the application to check for valid user. This is not the only way but you can have many more ways to organize the software model.

AddStudentAccForm.cs StartMenu.cs

Create an Object for "StartMenu.cs" in "AddStudentAccForm.cs" once you get the status "signedIn" as

StartMenu objStart = new StartMenu(signedIn);

In StartMenu.cs you can retrive this value in a Parameterized Constructor then you can use it accordingly

Class StartMenu
{
    StartMenu(string signedIn)
    {
        //use your value 
    }
}

For example if you want to pass the value for name from Form1 to Form2 just Add a static field declaration on Form2 to hold the Name value and from Form1 you can access those static field like that Form2.Name

public partial class Form2 : Form
{
    public static string Name;
    public static int value;
    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        label1.Text = Name+ value.ToString();
    }
}

and in Form1 if I just want to pass the value just do that.

in my case I will pass on Button event click

    private void button1_Click(object sender, EventArgs e)
    {
        Form2.value = 10;
        Form2.Name = "Felicio";
        Form2 form = new Form2();
        form.Show();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM