fg2210
fg2210

Reputation: 61

Preventing duplicate entries to excel

I'm creating a program in my free time to store info about my trading card collection. I was wondering is there any way to prevent duplicate entries into excel using the File.AppendAllText method. My current code is:

private void btnAdd_Click(object sender, EventArgs e)
    {
        Global.card.Add(new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text, lblCardTypeFinal.Text));
        string file = ("..\\Debug\\LOB.csv");
        string delimiter = ",";

        StringBuilder sb = new StringBuilder();

        foreach (Card card in Global.card)
        {
            sb.AppendLine(card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter + card.CardType);
        }

        File.AppendAllText(file, sb.ToString());

        MessageBox.Show("Card Added");
    }

When I try to add more than one card, the data of the previous one is entered into the excel file so it appears twice when I don't want it to. Thanks

Upvotes: 1

Views: 206

Answers (2)

Stuart
Stuart

Reputation: 5496

Try File.WriteAllText instead. File.AppendAllText will add the text to the bottom of the file.

Alternatively, you could do File.AppendAllLines for the card you are adding, like this:

private void btnAdd_Click(object sender, EventArgs e)
{
    string file = ("..\\Debug\\LOB.csv");
    string delimiter = ",";

    var card = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text, lblCardTypeFinal.Text)
    Global.card.Add(card);
    File.AppendAllLines(file, new[] {card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter + card.CardType});

    MessageBox.Show("Card Added");
}

Upvotes: 1

Shadowchaser
Shadowchaser

Reputation: 616

It looks that whenever you add single card you're appending all cards from Global.card, so I would get rid of foreach loop. You can just append this single card. Try something like:

Card newCard = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text, lblCardTypeFinal.Text)
Global.card.Add(newCard)
File.AppendAllText(file, newCard.CardNo + delimiter + newCard.CardName + delimiter + newCard.CardRarity + delimiter + newCard.CardType);

You also don't need StringBuilder, but I would work on ToString method for your Card class.

Upvotes: 0

Related Questions