2016-12-14 94 views
-2

我有2個窗體一個用於登錄,另一個用於調用依賴於登錄的功能。從另一種形式訪問變量

FORM1

public partial class Form1 : Form 
    { 
     static public string userId, userPassword; 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void label1_Click(object sender, EventArgs e) 
     { 

     } 

     private void button1_Click(object sender, EventArgs e) 
     { 

      if (Program.AllStudents.ContainsKey(userId)) 
      { 
       Program.studentdata student = Program.LoginStudent(userId); 
       if (student.password == userPassword) 
       { 
        Form3 studentcommands = new Form3(); 
        studentcommands.ShowDialog(); 
       } 
       else 
       { 
        MessageBox.Show("Wrong username or password", "Error", 
    MessageBoxButtons.OK, MessageBoxIcon.Error); 
        this.Close(); 
       } 
      } 
      else 
      { 
       MessageBox.Show("Wrong username or password", "Error", 
    MessageBoxButtons.OK, MessageBoxIcon.Error); 
       this.Close(); 
      } 

     } 

如果我想要訪問的另一種形式被稱爲學生的對象? 我該怎麼辦?

+1

搜索這個完全相同問題的數百萬重複中的任何一個。 –

+1

這是我甚至問過自己的問題,並且經常問這個問題。去檢查另一個答案,但爲了方便,有兩個選項AFAIK。首先,讓你的對象公開,通過Form1.objectName訪問它。或者你的第二個選擇是將對象作爲參數傳遞給第二個表單。 –

+0

爲了我的好奇心,這是一個班級任務嗎?幾個小時前提出了同樣的問題。 – Trey

回答

2

你可以在這個表格申報類型學生的Public property和使用Form1.Propertyname

從別人訪問了解更多關於性能在這個MSDN topic

或者只是聲明你的對象作爲Public