0

カスタム Associate オブジェクトをフィールドに渡し、ボタン クリック イベントの後にユーザー名とパスワードを追加したいと考えています。問題は、ボタン クリック イベントでオブジェクトのスコープが失われることです。どうすればこれを回避できますか? ここに私がこれまでに持っているコードがあります...

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 ;
    }
}
4

1 に答える 1

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 ;
  }
 }
于 2013-06-22T02:26:43.297 に答える