2013-06-22 89 views
0

我將自定義關聯對象傳遞到字段,並且我想在按鈕單擊事件後向其添加用戶名和密碼。問題是我在按鈕單擊事件中的對象鬆散範圍。我如何解決這個問題?這裏是我到目前爲止的代碼...按鈕單擊c後,將文本框數據添加到對象#

public partial class frmCredentials : Form 
    { 
     public frmCredentials(Associate _associate) 
     { 
      InitializeComponent(); 

     //Put in values for MES system and username 
     this.label1.Text = "Please enter your " + _associate.mesType + " password"; 
     this.txtUsername.Text = _associate.userName; 

     //Change form color for MES system 
     if (_associate.mesType == "FactoryWorks") 
     { 
      this.BackColor = System.Drawing.Color.Aquamarine; 
     } 
     else 
     { 
      this.BackColor = System.Drawing.Color.Yellow; 
     } 

    } 

    private void btnOk_Click(object sender, EventArgs e) 
    { 
     //Make sure associate has filled in fields 
     if (this.txtUsername.Text == "" || this.txtPassword.Text == "") 
     { 
      MessageBox.Show("You must enter a Username and Password"); 
      return; 
     } 
     this.Visible = false; 


     return ; 
    } 
} 

回答

0

的解決方案是創建一個實例字段中輸入Associate對象。然後在你的構造函數中設置實例字段值。

public partial class frmCredentials : Form 
{ 
    private Associate _associate; 

    public frmCredentials(Associate _associate) 
    { 
     InitializeComponent(); 

     this._associate = _associate; 

     //Put in values for MES system and username 
     this.label1.Text = "Please enter your " + _associate.mesType + " password"; 
     this.txtUsername.Text = _associate.userName; 

     //Change form color for MES system 
     if (_associate.mesType == "FactoryWorks") 
     { 
      this.BackColor = System.Drawing.Color.Aquamarine; 
     } 
     else 
     { 
      this.BackColor = System.Drawing.Color.Yellow; 
     } 

    } 

    private void btnOk_Click(object sender, EventArgs e) 
    { 
    // you can use _associate object in here since it's an instance field 

    //Make sure associate has filled in fields 
    if (this.txtUsername.Text == "" || this.txtPassword.Text == "") 
    { 
      MessageBox.Show("You must enter a Username and Password"); 
      return; 
     } 
     this.Visible = false; 
     return ; 
    } 
} 
+0

好吧,那太棒了! – user2499687

+1

this.associate = associate;是一個錯字。應該是this._associate = _associate,但我非常感謝你的幫助。現在效果很好。 – user2499687

+0

@ user2499687:你是對的..我只是修復它..謝謝! –

相關問題