簡體   English   中英

lambda 表達式事件偵聽器中的空字符串 Textbox.Text

[英]Empty String Textbox.Text inside lambda expression event listener

感覺我在這里缺少一些簡單的東西。 有一個看起來像這樣的表格:

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();

            
        }

    }

我不明白為什么 HandleID 方法中沒有表示所有文本框的 .text 值。 所有進來的都是空字符串。 我需要做些什么才能訪問這些值嗎? 謝謝!

對於那些有類似問題的人:

這里有兩種訂閱Click事件的方法。 第一個是:

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

第二個是:

private void updateCustomerBttn_Click(object sender, EventArgs e)

InitializeComponent()中訂閱。

現在,這里的問題是因為updateCustomerBttnHandleID之前被訂閱,所以當事件被調用時它也在HandleID之前被執行。 這意味着 Form 在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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM