WinForms中Lambda事件监听下TextBox.Text为空的问题排查
问题原因与解决方案
问题根源
你给按钮updateCustomerBttn绑定了两个Click事件:
- 设计器自动生成的
updateCustomerBttn_Click方法,里面调用了this.Close()关闭窗体 - 构造函数里通过lambda绑定的
HandleID调用
当按钮点击时,两个事件都会触发,但updateCustomerBttn_Click会先执行并关闭窗体——窗体关闭后,所有控件会被销毁/释放资源,此时HandleID再去访问文本框的.Text属性,自然只能拿到空字符串。而updateCustomerBttn_Click里能正常获取值,是因为它执行时窗体还没关闭。
解决方法
直接合并两个事件的逻辑,确保先处理业务代码,再关闭窗体,同时移除重复的事件绑定:
修改后的完整代码:
public partial class UpdateCustomerForm : Form { private UpdateCustomer _currentCustomer; public UpdateCustomerForm(UpdateCustomer customer) { InitializeComponent(); _currentCustomer = customer; // 移除这里的updateCustomerBttn.Click += ... 绑定 } private void updateCustomerBttn_Click(object sender, EventArgs e) { // 先执行更新逻辑 HandleID(_currentCustomer); // 再关闭窗体 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(); } }
额外说明
如果一定要保留两个事件绑定,需要确保HandleID在窗体关闭前执行,但这种做法没必要——同一个按钮的点击逻辑应该放在一处,避免出现时序问题和维护混乱。
内容的提问来源于stack exchange,提问作者idkwhatimdoing
相关产品推荐
相关产品推荐

