单击c#按钮后,将文本框数据添加到对象中

本文关键字:添加 数据 对象 文本 按钮 单击 | 更新日期: 2023-09-27 18:19:32

我将一个自定义的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 ;
    }
}

单击c#按钮后,将文本框数据添加到对象中

解决方案是为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 ;
  }
 }