简体   繁体   English

如何使用WPF应用程序向列表框条目添加ID以删除条目以及在列表中记录

[英]How to add id to listbox entry using WPF app to delete entries as well as record in list

I am trying to make a customer details system for uni that stores a customers name, email, telephone number, skype, etc. 我正在尝试为uni创建一个客户详细信息系统,该系统存储客户名称,电子邮件,电话号码,skype等。

I have it all set up so that you can add, delete, and find there details in the list. 我已经全部设置好了,以便您可以添加,删除和在列表中找到详细信息。 The list only stays in memory while the program runs. 该列表仅在程序运行时保留在内存中。 I have an extra advanced task where I have to add the customers details entered to the list to a listbox. 我还有一项高级任务,必须将输入到列表中的客户详细信息添加到列表框中。 It should show their ID number which they have automatically assigned and their name. 它应该显示他们已自动分配的ID号和姓名。 When you click on it, it is supposed to show their full details list on the app. 当您单击它时,它应该在应用程序上显示其完整的详细信息列表。

The problem I am having is that when I add an entry to the listbox, it doesn't really have any kind of ID that I can use to search the list for that person I have had to set up taking the name of the listbox entry, turning it into a string and cutting off the name part, leaving the ID. 我遇到的问题是,当我将一个条目添加到列表框时,它实际上没有任何ID可用于搜索我必须用该列表框条目的名称设置的人员的ID。 ,将其转换为字符串并切断名称部分,保留ID。 doing this I can delete the entry at the same time as the actual list record. 这样做,我可以与实际列表记录同时删除该条目。 But I also have an ID textbox that when you enter the ID of a person and click the delete button, it deletes the list record, but not the listbox entry. 但是我还有一个ID文本框,当您输入一个人的ID并单击Delete按钮时,它会删除列表记录,而不是列表框条目。 How do I get it to delete the entry as well when it is not currently selected? 当当前未选中该条目时,如何将其删除?

I also have a problem where if I add two people and try to search for the first person. 我还有一个问题,如果我添加两个人并尝试搜索第一个人。 it says their ID does not exist? 它说他们的身份证不存在? It also only shows the last person entered details when you click on the first listbox entry. 当您单击第一个列表框条目时,它也仅显示最后输入的详细信息。

Here is the WPF: 这是WPF:

在此处输入图片说明

Here is my code for the buttons and textboxes: 这是我的按钮和文本框代码:

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
            {
            }
        }
    }
}

This is my customer class: 这是我的客户类别:

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

namespace BusinessObjects
{
    public class Customer
    {
        //Variables to hold each specific detail for each customer for adding to the list.
        private int _customerID;
        private string _telephone;
        private string _firstName;
        private string _secondName;
        private string _email;
        private string _skypeID;
        private string _prefContact;

        //Get/Set for using ID value.
        public int ID
        {
            get
            {
                return _customerID;
            }
            set
            {
                _customerID = value;
            }
        }

        //Get/Set for using First Name value.
        public string FirstName
        {
            get
            {
                return _firstName;
            }
            set
            {
                _firstName = value;
            }
        }

        //Get/Set for using Second Name value.
        public string SecondName
        {
            get
            {
                return _secondName;
            }
            set
            {
                _secondName = value;
            }
        }

        //Get/Set for using Skype value.
        public string SkypeID
        {
            get
            {
                return _skypeID;
            }
            set
            {
                _skypeID = value;
            }
        }

        //Get/Set for using Telephone value.
        public string Telephone
        {
            get
            {
                return _telephone;
            }
            set
            {
                _telephone = value;
            }
        }

        //Get/Set for using Email value.
        public string Email
        {
            get
            {
                return _email;
            }
            set
            {
                _email = value;
            }
        }

        //Get/Set for using preferred Contact value.
        public string PrefContact
        {
            get
            {
                return _prefContact;
            }
            set
            {
                _prefContact = value;
            }
        }

        public string PrintDetails()
        {
            return "Found:" +
                 "\nName: " + FirstName + " " + SecondName +
                 "\nEmail: " + Email +
                 "\nSkype: " + SkypeID +
                 "\nTelephone: " + Telephone +
                 "\nPreferred Contact: " + PrefContact +
                 "\nID No: " + ID;
        }
    }
}

And this is my mailing list class: 这是我的邮件列表类:

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

Unless you want to use mentioned data bindings you can try this. 除非您要使用提到的数据绑定,否则可以尝试一下。

Add ListBoxItem instead of string, that way you can access ID without parsing. 添加ListBoxItem而不是字符串,这样您就可以在不解析的情况下访问ID。

lbxCustomers.Items.Add(new ListBoxItem 
{ 
    Tag = cust.ID, 
    Content = cust.FirstName + " " + cust.SecondName
});

Removing from listbox: 从列表框中删除:

ListBoxItem itemToDelete = null;

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

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

You might need to cast some variables into proper types. 您可能需要将一些变量转换为适当的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM