winforms 空字符串文本框,lambda表达式事件侦听器中的文本

iklwldmw  于 2023-01-09  发布在  其他
关注(0)|答案(1)|浏览(86)

我觉得我在这里遗漏了一些简单的东西。有一个看起来像这样的表单:

public partial class UpdateCustomerForm : Form
    {
        public UpdateCustomerForm(UpdateCustomer customer)
        {
            InitializeComponent();      

            updateCustomerBttn.Click += (sender, e) => HandleID(customer);

        }

        private void updateCustomerBttn_Click(object sender, EventArgs e)
        {
            string customerName = nameTb.Text; // This works
            this.Close();

        }

        private void HandleID(UpdateCustomer customer)
        {
            //all below values are empty

            UpdateCustomer customerToUpdate = new UpdateCustomer()
            {
                CustomerID = customer.CustomerID,
                CustomerName = nameTb.Text,
                Address1 = addressTb.Text,
                Address2 = address2Tb.Text,
                Phone = phoneTb.Text,
                City = cityTB.Text,
                Country = countryTb.Text

            };

            Customer.UpdateCustomer(customerToUpdate);

            CustomerForm CustomerForm = (CustomerForm)Application.OpenForms["CustomerForm"];
            CustomerForm.PopulateDGV();

            
        }

    }

我不明白为什么所有文本框的.text值都没有在HandleID方法中表示出来。所有的值都是空字符串。我需要做些什么才能访问这些值吗?谢谢!

bn31dyow

bn31dyow1#

对于那些有类似问题的人:
这里订阅Click事件的方法有两个,第一个是:

updateCustomerBttn.Click += (sender, e) => HandleID(customer);

第二个是

private void updateCustomerBttn_Click(object sender, EventArgs e)

其在InitializeComponent()中预订。
现在的问题是,因为updateCustomerBttnHandleID之前被订阅,所以当调用事件时,它也在HandleID之前被执行,这意味着表单在HandleID执行之前被关闭,这就是问题的原因。
当然,你可以改变订阅这两个方法的顺序,但是你已经可以看到,随着时间的推移,这会变得非常混乱,所以更好的选择是将this.Close()移到HandleID,或者--如果你想非常简洁的话--将它添加到构造函数的lambda中:

public partial class UpdateCustomerForm : Form
{
    public UpdateCustomerForm(UpdateCustomer customer)
    {
        InitializeComponent();      
        updateCustomerBttn.Click += (sender, e) => {
            HandleID(customer);
            this.Close();
        };
    }

    private void HandleID(UpdateCustomer customer)
    {
        UpdateCustomer customerToUpdate = new UpdateCustomer()
        {
            CustomerID = customer.CustomerID,
            CustomerName = nameTb.Text,
            Address1 = addressTb.Text,
            Address2 = address2Tb.Text,
            Phone = phoneTb.Text,
            City = cityTB.Text,
            Country = countryTb.Text
        };

        Customer.UpdateCustomer(customerToUpdate);

        CustomerForm CustomerForm = (CustomerForm)Application.OpenForms["CustomerForm"];
        CustomerForm.PopulateDGV();
    }
}

相关问题