Comparing multiple Textbox fields to check for duplicity

Asked

Viewed 613 times

0

I’m developing a basic C# program where the user will enter values through a barcode reader. It will be saved in an Excel spreadsheet for a future report.

My problem is that there are situations where the user beeps the same code twice in different textbox.

I was wondering if, by clicking on my button, Salvar, had an event to compare all my textbox and check for repeated values, preventing to save duplicate information.

Below is my Button Add code:

private void BtnAdicionar_Click(object sender, EventArgs e)
{                
    Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
    Microsoft.Office.Interop.Excel.Workbook sheet = Excel.Workbooks.Open("C:\\Users\\Core i3\\Desktop\\EtiqMasterBoxTornozeleira.xlsx");
    Microsoft.Office.Interop.Excel.Worksheet x = Excel.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;

    Excel.Range userRanger = x.UsedRange;

    int countRecords = userRanger.Rows.Count;
    int add = countRecords + 1;
}

2 answers

2


A simple way to do this is to use an Array

        Int64[] valores = new Int64[3];
        valores[0] = Convert.ToInt64(textBox1.Text);
        valores[1] = Convert.ToInt64(textBox2.Text);
        valores[2] = Convert.ToInt64(textBox3.Text);


        int quant_campos = valores.Length;
        var groups = valores.Distinct().ToList();

        if(quant_campos > groups.Count)
        {

            MessageBox.Show("Existe Campos Duplicados");
        }
  • Thanks for the help, it worked here, now I just need to implement a method for him not to let save even with duplicate fields, which is what is still happening, but he already accuses that there are duplicate fields. Thank you

0

Some things haven’t been made very clear, but I’ll try to help. You comment on iterating the texts, and so I will conclude that you do not need to confirm the information that has already been recorded previously in your spreadsheet.

All right:

Save each barcode (string) in a collection of strings of your choice; but first, confirm that within that list do not yet contain this "barcode" that will be saved through the method Contains:

ICollection<string> codesCollection = new List<string>();

private void AddBarCode(string barcode)
{
    bool isDuplicatedCode = codesCollection.Contains(barcode);

    if(isDuplicatedCode)
        throw new ArgumentException("O código de barras já foi adicionado.").

    codesCollection.add(barcode);
}
  • Your also worked friend, thanks for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.