Как предотвратить дублирование записей в списке - PullRequest
1 голос
/ 17 апреля 2019

Я должен создать программу, которая читает из выходного файла, а также добавить ДОПОЛНИТЕЛЬНЫЙ текст к этому выходному файлу с помощью метода AppendText, чтобы ничто в текстовом файле не было переопределено. Вы можете добавлять вещи в список через текстовое поле, но я пытаюсь предотвратить повторяющиеся записи. Я внедрил код, который якобы предотвращает несколько записей, но он не работает должным образом. Это дает сообщение, что я установил «Дублирующая запись», но все равно добавляет запись. ЛЮБОЙ СПОСОБ ИСПРАВИТЬ ЭТО? Пожалуйста, помогите СПАСИБО.

Это код

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;


namespace BIT_UNITS
{
public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void displayButton_Click(object sender, EventArgs e)
    {
        try
        {
            //Variables
            string unitsList;

            //declare streamReader variable
            StreamReader inputFile;

            //Open file & get units list
            inputFile = File.OpenText("BITS_Units.txt");

            //Clear anything currently in the listbox
            unitsListBox.Items.Clear();

            //Read the file's Contents
            while (!inputFile.EndOfStream)
            {
                //Get Units List
                unitsList = inputFile.ReadLine();

                //Display the units list in the listbox
                unitsListBox.Items.Add(unitsList);
            }
            //close the file
            inputFile.Close();

        }
        catch 
        {
            MessageBox.Show("Error");
        }
    }

    private void addUnitButton_Click(object sender, EventArgs e)
    {
        try
        {
            //Declare streamwriter variable
            StreamWriter outputFile;


            //Open file and get a streamwriter object
            outputFile = File.AppendText("BITS_Units.txt");

            //Record inputs to the file
            outputFile.WriteLine(addUnitsTextBox.Text);

            //Close the file 
            outputFile.Close();

            //Determine wether textbox is filled
            if (addUnitsTextBox.Text== Text)
            {
            //Display message
            MessageBox.Show("Unit was successfully added.");
            }

            //Determine wether textbox is filled                
            if (addUnitsTextBox.Text == "")
            {
                MessageBox.Show("Please enter a unit name to add to the list.");

            }

            if (unitsListBox.Items.Contains(addUnitsTextBox.Text))
            {

                MessageBox.Show("This unit already exists");
            }

            else 
            {
                unitsListBox.Items.Add(addUnitsTextBox.Text);
                addUnitsTextBox.Text = "";

            }

          }
        catch (Exception)
        {
            MessageBox.Show("error");
        }
    }

    private void clearButton_Click(object sender, EventArgs e)
    {
        try
        {
            //Clear data
            addUnitsTextBox.Text = "";
            unitsListBox.Items.Clear();
        }
        catch (Exception)
        {
            MessageBox.Show("Error");
        }
    }

    private void exitButton_Click(object sender, EventArgs e)
    {
        //Close the form
        this.Close();
    }
}
}

1 Ответ

2 голосов
/ 17 апреля 2019

Перед добавлением элемента в список проверьте, не существует ли он в списке.

     if (!unitsListBox.Items.Contains(unitsList) )
     {
          unitsListBox.Items.Add(unitsList);
     }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...