Search code examples
c#formsshow-hide

Hide and Show Code doesnt work on other forms


In form 1

public void button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"Data Source=.\ALLENSQL;Initial Catalog=TITOMSLogin;Integrated Security=True");
            SqlDataAdapter sdf = new SqlDataAdapter("select usertype, fullname, position from login where username= '" + txtuser.Text + "' and password='" + txtpass.Text + "'", con);
            DataTable dt = new DataTable();
            sdf.Fill(dt);
            string fullname = dt.Rows[0]["FullName"].ToString();
            string position = dt.Rows[0]["Position"].ToString();
            if (dt.Rows.Count == 1)
             {
                 this.Hide();
                 if (dt.Rows[0]["Usertype"].ToString() == "Admin")
                 {
                    Form2Admin ss = new Form2Admin(position + ": " + fullname);
                    Form3Admin sa = new Form3Admin(position + ": " + fullname);
                    Form5 sw = new Form5(position + ": " + fullname);
                    ss.Show();
                    sa.Hide();
                    sw.Hide();
                 }

now this code doesn't work in other forms

        private void button2_Click(object sender, EventArgs e)
        {
            this.Hide();
            Form3Admin.Show();
        }

this is the scenarios I am trying to achieve:

  1. After pressing login form2 will show up, form 3 and form 4 is hidden.
  2. button in form 2 is press (Form 2 will hide, Form 3 will show).
  3. button in form 3 is press (Form 3 will hide, Form 4 will show).
  4. button in form 4 is press (form 4 will hide, Form 2 will show but all data written before must still be there) and so on to the other forms.

Solution

  • You have to use the same actual Form3Admin instance to Show it. Keep Form3Admin sa instance as a class variable and use that instance when you want to show it.

    private void button2_Click(object sender, EventArgs e)
    {
        this.Hide();
        sa.Show();
    }