C# 如何使用WPF应用程序向列表框条目添加id以删除条目以及列表中的记录

C# 如何使用WPF应用程序向列表框条目添加id以删除条目以及列表中的记录,c#,wpf,listbox,C#,Wpf,Listbox,我正在尝试为uni制作一个客户详细信息系统,该系统存储客户姓名、电子邮件、电话号码、skype等 我已将其全部设置好,以便您可以添加、删除并在列表中查找详细信息。该列表仅在程序运行时保留在内存中。我有一个额外的高级任务,我必须将输入到列表中的客户详细信息添加到列表框中。它应该显示他们自动分配的ID号和姓名。当你点击它时,它应该会在应用程序上显示他们的全部详细信息列表 我遇到的问题是,当我在列表框中添加一个条目时,它实际上没有任何类型的ID,我可以使用它在列表中搜索我必须设置的那个人,将列表框条目

我正在尝试为uni制作一个客户详细信息系统,该系统存储客户姓名、电子邮件、电话号码、skype等

我已将其全部设置好,以便您可以添加、删除并在列表中查找详细信息。该列表仅在程序运行时保留在内存中。我有一个额外的高级任务,我必须将输入到列表中的客户详细信息添加到列表框中。它应该显示他们自动分配的ID号和姓名。当你点击它时,它应该会在应用程序上显示他们的全部详细信息列表

我遇到的问题是,当我在列表框中添加一个条目时,它实际上没有任何类型的ID,我可以使用它在列表中搜索我必须设置的那个人,将列表框条目的名称转换为字符串并删除名称部分,保留ID。这样我可以在删除实际列表记录的同时删除条目。但我也有一个ID文本框,当你输入一个人的ID并单击delete按钮时,它会删除列表记录,但不会删除listbox条目。当当前未选中条目时,如何使其删除该条目

我也有一个问题,如果我添加两个人并尝试搜索第一个人。上面说他们的身份证不存在?当您单击第一个列表框条目时,它还仅显示上次输入的人员详细信息

以下是WPF:

以下是我的按钮和文本框代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BusinessObjects;

namespace Demo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //Object to hold details for each customer.
        Customer cust = new Customer();
        //List to hold details of each customer.
        private MailingList store = new MailingList();
        //Variable to set starting ID number.
        private int ID = 10001;

        public MainWindow()
        {
            InitializeComponent();
        }

        // Button for Adding a customer with a specific assigned ID number.
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // If statements that catches errors within textboxes
                if (txtFName.Text == "" || txtFName.Text.Length > 15 || Regex.IsMatch(txtFName.Text, @"^[0-9]+$"))
                {
                    throw new Exception();
                }
                else if (txtSName.Text == "" || txtSName.Text.Length > 25 || Regex.IsMatch(txtSName.Text, @"^[0-9]+$"))
                {
                    throw new Exception();
                }
                else if (txtEmail.Text == "" || !Regex.IsMatch(txtEmail.Text, @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$"))
                {
                    throw new Exception();
                }
                else if (txtSkype.Text == "" || txtSkype.Text.Length > 32)
                {
                    throw new Exception();
                }
                else if (txtTelephone.Text == "" || txtTelephone.Text.Length > 11 || Regex.IsMatch(txtTelephone.Text, @"^[a-zA-Z]+$"))
                {
                    throw new Exception();
                }
                else if (txtPrefContact.Text == "" || !Regex.IsMatch(txtPrefContact.Text, @"^(?:tel|email|skype)+$"))
                {
                    throw new Exception();
                }

                // Stores the details of the textboxes into the customer details for each list entry.
                cust.ID = ID;
                cust.FirstName = txtFName.Text;
                cust.SecondName = txtSName.Text;
                cust.Email = txtEmail.Text;
                cust.SkypeID = txtSkype.Text;
                cust.Telephone = txtTelephone.Text;
                cust.PrefContact = txtPrefContact.Text;

                // Adds the details of the person above to the list and increases the ID number by one for the next entry.
                store.add(cust);
                ID++;

                lbxCustomers.Items.Add(cust.ID + " " +cust.FirstName + " " + cust.SecondName);

                // Shows user the details of the person added to the list.
                MessageBox.Show("Name: " + cust.FirstName + " " + cust.SecondName +
                              "\nEmail: " + cust.Email +
                              "\nSkype: " + cust.SkypeID +
                              "\nTelephone: " + cust.Telephone +
                              "\nPreferred Contact: " + cust.PrefContact +
                              "\nID No: " + cust.ID);

                // Clears all textboxes for next entry after adding a customer.
                txtFName.Clear();
                txtSName.Clear();
                txtEmail.Clear();
                txtSkype.Clear();
                txtTelephone.Clear();
                txtPrefContact.Clear();
            }
            catch
            {
                // IF statements that displays errors after catching them
                if (txtFName.Text == "" || txtFName.Text.Length > 15 || Regex.IsMatch(txtFName.Text, @"^[0-9]+$"))
                {
                    MessageBox.Show("You must enter a first name within 15 characters." +
                                  "\nNo numbers allowed.");
                    // Clears all textboxes for next entry after throwing exception.
                    txtFName.Clear();
                    txtSName.Clear();
                    txtEmail.Clear();
                    txtSkype.Clear();
                    txtTelephone.Clear();
                    txtPrefContact.Clear();
                    return;
                }
                else if (txtSName.Text == "" || txtSName.Text.Length > 15 || Regex.IsMatch(txtSName.Text, @"^[0-9]+$"))
                {
                    MessageBox.Show("You must enter a second name within 25 characters." +
                                  "\nNo numbers allowed.");
                    //Clears all textboxes for next entry after throwing exception.
                    txtFName.Clear();
                    txtSName.Clear();
                    txtEmail.Clear();
                    txtSkype.Clear();
                    txtTelephone.Clear();
                    txtPrefContact.Clear();
                    return;
                }
                else if (txtEmail.Text == "" || !Regex.IsMatch(txtEmail.Text, @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$"))
                {
                    MessageBox.Show("You haven't entered a valid email address.");
                    // Clears all textboxes for next entry after throwing exception.
                    txtFName.Clear();
                    txtSName.Clear();
                    txtEmail.Clear();
                    txtSkype.Clear();
                    txtTelephone.Clear();
                    txtPrefContact.Clear();
                    return;
                }
                else if (txtSkype.Text == "" || txtSkype.Text.Length > 32)
                {
                    MessageBox.Show("You haven't entered a valid Skype address." +
                                  "\nMust be within 32 letters and numbers.");
                    // Clears all textboxes for next entry after throwing exception.
                    txtFName.Clear();
                    txtSName.Clear();
                    txtEmail.Clear();
                    txtSkype.Clear();
                    txtTelephone.Clear();
                    txtPrefContact.Clear();
                    return;
                }
                else if (txtTelephone.Text == "" || txtTelephone.Text.Length > 11 || Regex.IsMatch(txtTelephone.Text, @"^[a-zA-Z]+$"))
                {
                    MessageBox.Show("You must enter an 11 digit phone number." +
                                  "\nNo Letters allowed.");
                    // Clears all textboxes for next entry after throwing exception.
                    txtFName.Clear();
                    txtSName.Clear();
                    txtEmail.Clear();
                    txtSkype.Clear();
                    txtTelephone.Clear();
                    txtPrefContact.Clear();
                    return;
                }                
                else if (txtPrefContact.Text == "" || !Regex.IsMatch(txtPrefContact.Text, @"^(?:tel|email|skype)+$"))
                {
                    MessageBox.Show("You have not entered the correct preferred contact." +
                                  "\nPlease enter either email, skype or tel.");
                    // Clears all textboxes for next entry after throwing exception.
                    txtFName.Clear();
                    txtSName.Clear();
                    txtEmail.Clear();
                    txtSkype.Clear();
                    txtTelephone.Clear();
                    txtPrefContact.Clear();
                    return;
                }
            }
        }

        // Button for deleting a specific customer with their specific ID.
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            // Makes sure the selected listbox entry is not negative.
            if (lbxCustomers.SelectedIndex >= 0)
            {
                // Get the currently selected item in the ListBox, convert it to a string and then cut off the name leaving only the id number.
                string curItem = lbxCustomers.SelectedItem.ToString();
                string result1 = curItem.Remove(6, curItem.Length - 6);

                // Allows the text from result 1 to be converted back to an integer to use for locating customer.
                int ID = Int32.Parse(result1);

                // Deletes the selected listbox entry and deletes that person from the list.
                lbxCustomers.Items.RemoveAt(lbxCustomers.SelectedIndex);
                store.delete(ID);

                // Stops from continuing on to check if an ID is in the ID textbox.
                return;
            }

            try
            {
                // Allows the text in the ID textbox to be changed to an integer to be used for checking the ID.
                int id = Int32.Parse(txtID.Text);

                /*If the ID number entered is not found in the list, 
                an error message is displayed to say the customer does not exist.
                If the ID does exist, deletes that customer. */

                if (store.find(id) == null)
                {
                    // Displays error message to tell user that this customer does not exist.
                    MessageBox.Show("Invalid ID!" +
                                  "\nNo Customer with this ID exists!");
                }
                else
                {
                    lbxCustomers.Items.Remove(store.ids);

                    // Displays the details of customer with specific ID.
                    store.delete(id);

                    // Displays the details of the customer deleted
                    MessageBox.Show("Deleted Customer:" +
                                  "\nName: " + cust.FirstName + " " + cust.SecondName +
                                  "\nEmail: " + cust.Email +
                                  "\nSkype: " + cust.SkypeID +
                                  "\nTelephone: " + cust.Telephone +
                                  "\nPreferred Contact: " + cust.PrefContact +
                                  "\nID No: " + cust.ID);
                }
            }
            catch
            {
                MessageBox.Show("You did not enter a correct ID!");
                return;
            }
        }

        // Button for Finding a specific customer with their specific ID.
        private void btnFind_Click(object sender, RoutedEventArgs e)
        {
            // Checking for error
            try
            {
                // Allows the text in the ID textbox to be changed to an integer to be used for checking the ID.
                int id = Int32.Parse(txtID.Text);

                /*If the ID number entered is not found in the list, 
                an error message is displayed to say the user does not exist.
                If the ID does exist, shows the user the details of the person with that ID. */
                if (store.find(id) == null)
                {
                    // Displays error message to tell user that this customer does not exist.
                    MessageBox.Show("Invalid ID!" +
                                    "\nNo Customer with this ID exists!");
                }
                else
                {
                    // Displays the details of customer with specific ID.
                    MessageBox.Show(store.Display(id));
                }
            }
            catch
            {
                MessageBox.Show("You did not enter a correct ID!");
            }
        }

        private void lbxCustomers_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Allows user to delete a listbox entry without program crashing whilst still having one selected to show details.
            try
            {
                // Get the currently selected item in the ListBox, convert it to a string and then cut off the name leaving only the id number.
                string curItem = lbxCustomers.SelectedItem.ToString();
                string result1 = curItem.Remove(6, curItem.Length - 6);

                // Allows the text from result 1 to be converted back to an integer to use for locating customer.
                int ID = Int32.Parse(result1);

                // Shows the user the selected customers full details.
                MessageBox.Show(cust.Display(ID));
            }
            catch
            {
            }
        }
    }
}
这是我的邮件列表类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BusinessObjects
{
    public class MailingList
    {
        private List<Customer> _list = new List<Customer>();

        public void add(Customer newCustomer)
        {
            _list.Add(newCustomer);
        }

        public Customer find(int id)
        {
            foreach (Customer c in _list)
            {
                if (id == c.ID)
                {
                    return c;
                }
            }

            return null;

        }

        public void delete(int id)
        {
            Customer c = this.find(id);
            if (c != null)
            {
                _list.Remove(c);
            }

        }

        public List<int> ids
        {
            get
            {
               List<int> res = new List<int>();
               foreach(Customer p in _list)
                   res.Add(p.ID);
                return res;
            }

        }

        public void ShowDetails()
        {
            foreach (Customer c in _list)
            {
                MessageBox.Show(c.PrintDetails());
            }
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Windows.Forms;
命名空间BusinessObjects
{
公共类邮件列表
{
私有列表_List=新列表();
公共作废添加(客户新客户)
{
_列表。添加(新客户);
}
公共客户查找(int id)
{
foreach(客户名单中的c)
{
if(id==c.id)
{
返回c;
}
}
返回null;
}
公共无效删除(int-id)
{
客户c=此。查找(id);
如果(c!=null)
{
_删除(c)项;
}
}
公共列表ID
{
收到
{
List res=新列表();
foreach(客户名单中的p)
res.Add(p.ID);
返回res;
}
}
公开资料
{
foreach(客户名单中的c)
{
Show(c.PrintDetails());
}
}
}
}

除非您想使用上述数据绑定,否则可以尝试此方法

添加ListBoxItem而不是字符串,这样您就可以访问ID而无需解析

lbxCustomers.Items.Add(new ListBoxItem 
{ 
    Tag = cust.ID, 
    Content = cust.FirstName + " " + cust.SecondName
});
正在从列表框中删除:

ListBoxItem itemToDelete = null;

foreach (ListBoxItem item in listbox.Items)
{
    if (item.Tag == idToDelete)
    {
        itemToDelete = item;
        break;
    }
}

if(itemToDelete != null)
{
    lbxCustomers.Items.Remove(itemToDelete);
}

您可能需要将一些变量强制转换为适当的类型。

我们需要一个帮助,而不是完整的项目代码。我将使用数据绑定和将列表框绑定到MailingList类,这里有一个非常有用的教程介绍如何做这件事。我已编辑以显示所有类。您真的需要添加那么多代码吗?已尝试将删除代码添加到我按ID号删除的else语句中。但是它说没有可访问的扩展方法“FirstOrDefault”。还有其他方法可以替代吗?这非常有帮助,我觉得您刚刚回答了我的问题,如何同时删除列表框条目。但是我刚刚意识到我的find函数不能正常工作。我正在尝试执行store.find(id)以与if语句中的item.tag进行比较。但是store.find(id)只是返回一个对象,而不是实际的id。我的find函数有什么错?
store.find(item.Tag)
如果Tag是
object
类型,则必须首先将其强制转换为
int
((ListBoxItem)listbox.SelectedItem).Tag
应该可以工作,因为您只有一个Customer实例,每次“添加”新实例时都会覆盖它,然后将其添加到列表中。
ListBoxItem itemToDelete = null;

foreach (ListBoxItem item in listbox.Items)
{
    if (item.Tag == idToDelete)
    {
        itemToDelete = item;
        break;
    }
}

if(itemToDelete != null)
{
    lbxCustomers.Items.Remove(itemToDelete);
}