删除按钮不删除ListBox中的项目

时间:2016-07-26 19:30:29

标签: c# listbox

通过上一个问题的答案和帮助。我现在遇到了另一个问题。

我的btnDelete_MouseClick()事件未删除存储在textBox中的客户信息。

我希望它能收集如下信息:Ashton Smith 864123456789

然后当相应的textFields中出现完全相同的信息时,我点击了delete按钮,它将其从listBox中删除。

这是我到目前为止所拥有的。它运行但不会从listBox中删除客户。

 public partial class Form1 : Form
{
    Customer cust;
    public Form1()
    {
        InitializeComponent();

        tbxFirstName.CharacterCasing = CharacterCasing.Upper;
        tbxFirstName.MaxLength = 35; 
        tbxLastName.CharacterCasing = CharacterCasing.Upper;
        tbxLastName.MaxLength = 35;
        tbxPhone.MaxLength = 10;
        listBoxDatabase.Name = "CUSTOMERS";
    }

    private void btnAddCustomer_MouseClick(object sender, MouseEventArgs e)
    {
        //string customer = tbxFirstName.Text + " " + tbxLastName.Text + " " + tbxPhone.Text;
        cust = new Customer(tbxFirstName.Text, tbxLastName.Text, tbxPhone.Text);


        if (listBoxDatabase.Items.Cast<Customer>().Any(x => x.ToString() == cust.ToString()))
        {

            MessageBox.Show("Customer Already Exist!", "ERROR");
        }
        else
        {
            listBoxDatabase.Items.Add(cust);
        }
    }

    private void btnDelete_MouseClick(object sender, MouseEventArgs e)
    {
        Customer custToDelete = listBoxDatabase.Items.Cast<Customer>().FirstOrDefault(x => x.ToString() == cust.ToString());

        if (custToDelete != null)
        {
            listBoxDatabase.Items.Remove(cust);
        }
        else
        {
            MessageBox.Show("No Customer Found!", "ERROR");
        }
    }

    private void listBoxDatabase_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (listBoxDatabase.SelectedIndex != -1)
        {
            Customer cust = listBoxDatabase.Items[listBoxDatabase.SelectedIndex] as Customer;
            tbxFirstName.Text = cust.getFirstName;
            tbxLastName.Text = cust.getLastName;
            tbxPhone.Text = cust.getPhone;
        }
    }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

您删除逻辑错误。您不应该使用global来比较对象。您可以将ListBox的Selected Item转换为您的特定类型,然后从items集合中删除它:

.ToString()