Как добавить идентификатор в запись списка с помощью приложения WPF для удаления записей, а также записи в списке - PullRequest
0 голосов
/ 29 октября 2018

Я пытаюсь создать систему сведений о клиенте для универа, в которой хранятся имя, адрес электронной почты, номер телефона, Skype и т. Д.

У меня все настроено так, что вы можете добавлять, удалять и находить там детали в списке. Список остается в памяти только во время работы программы. У меня есть дополнительная сложная задача, где я должен добавить данные клиентов, введенные в список, в список. Он должен показать их идентификационный номер, который они автоматически присвоили, и их имя. Когда вы нажимаете на нее, она должна отображать полный список деталей в приложении.

Проблема, с которой я сталкиваюсь, заключается в том, что, когда я добавляю запись в список, на самом деле у нее нет никакого идентификатора, который я мог бы использовать для поиска в списке того человека, которого я должен был настроить, принимая имя запись списка, превращая ее в строку и обрезая часть имени, оставляя идентификатор. делая это, я могу удалить запись одновременно с фактической записью списка. Но у меня также есть текстовое поле идентификатора, которое, когда вы вводите идентификатор человека и нажимаете кнопку удаления, удаляет запись списка, но не запись списка. Как заставить его удалить запись, если она еще не выбрана?

У меня также есть проблема, когда я добавляю двух человек и пытаюсь найти первого человека. это говорит, что их удостоверение личности не существует? Он также показывает только последние введенные данные, когда вы нажимаете на первую запись списка.

Вот WPF:

enter image description here

Вот мой код для кнопок и текстовых полей:

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;

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

А это мой класс списка рассылки:

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

1 Ответ

0 голосов
/ 29 октября 2018

Если вы не хотите использовать упомянутые привязки данных, вы можете попробовать это.

Добавьте ListBoxItem вместо строки, чтобы вы могли получить доступ к идентификатору без разбора.

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

Возможно, вам придется преобразовать некоторые переменные в соответствующие типы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...