C# - Read txt file and return value in textbox

Asked

Viewed 151 times

0

I am making an application that from a selection of Combobox, it reads the txt file (containing two columns) and returns me the value of the same row but column 1 (column 2 would be the value of Combobox). I can return the values, but it is returning the values of column 1, but the next line.

I have managed to return other values of other textbox, combobox, because there is the same application, but only the one that I am not getting.

I’ve tried everything, I’ve searched, I’ve read forums, but I can’t find where my mistake is.

Code in class:

public class Arquivo_Dados
{
    public List<string[]> Dados;
    public List<double> fmtDados;

    public void LoadDados() // Chama o arquivo e lê todas linhas separando por ';'. 
    {
        Dados = File.ReadAllLines(@"caminho do meu arquivo").Select(l => l.Split(';').Select(v => v.Trim()).ToArray()).ToList();

        fmtDados = Dados.Select(lDados => double.Parse(lDados[0])).ToList();
    }

    public string ReceberMaiorValorDiametro(string input) // Ler os dados do arquivo da coluna 1 retornar os valores da coluna 2 (Diametro - mm).
    {
        if (!double.TryParse(input, out double dbDiam))
        {
            return null;
        }

        int index = 0;
        double min = double.MaxValue;

        for (int i = 0; i < fmtDados.Count; i++)
        {
            if (fmtDados[i] < dbDiam) // Se menor que o valor a entrada (Textbox), ignora.
            {
                continue;
            }

            var difDiam = Math.Abs(fmtDados[i] - dbDiam); // Diferença entre a entrada (Textbox) e o que está no arquivo. 

            if (difDiam < min) // Se a diferença for menor que a anterior, retorna.
            {
                min = difDiam;
                index = i;
            }
        }

        return Dados[index][1]; //Retorna a coluna 2.
    }

    public string ReceberMaiorValorCarga(string input) // Ler os dados do arquivo da coluna 2 retornar os valores da coluna 1 (Carga - kN).
    {
        if (!double.TryParse(input, out double dbCarga))
        {
            return null;
        }

        int index = 0;
        double min = double.MaxValue;

        for (int i = 0; i < fmtDados.Count; i++)
        {
            if (fmtDados[i] < dbCarga) // Se menor que o valor a entrada (Textbox), ignora.
            {
                continue;
            }

            var difCarga = Math.Abs(fmtDados[i] - dbCarga); // Diferença entre a entrada (Textbox) e o que está no arquivo. 

            if (difCarga < min) // Se a diferença for menor que a anterior, retorna.
            {
                min = difCarga;
                index = i;
            }
        }

        return Dados[index][0]; //Retorna a coluna 1.
    }

     public string[] ListarColuna2()
     {
         return Dados.Select(dCol2 => dCol2[1]).ToArray();
     }

     public string[] BuscarColuna2(int index)
     {
         return Dados[index];
     }
}

The codes ReceberMaiorValorDiametro and ReceberMaiorValorCargaare working just the ListarColuna2() and BuscarColuna2 Not returning me correctly to the row I want (the column is right).

On the form I’m calling them:

var numDiam = Arq_Dados.ReceberMaiorValorDiametro(txtFc.Text);
ValorDc = double.Parse(cmbNumeros.Text = numDiam?.ToString());

var numCarga = Arq_Dados.ReceberMaiorValorCarga(txtFc.Text);
FcAdopted = double.Parse(txtNum.Text = numCarga?.ToString());

The values of the generated numDiam are going to the combobox, and there are other values already registered in the combobox (they are same values in the txt file) And I want from a selection in the combobox it read the file again and returns the values (he’s returning me to the right column, but the line isn’t, it’s returning me to the next line).

Code I entered in Combobox:

var Arq_Dados = new Arquivo_Dados();
Arq_Dados.LoadDados();

cmbNumeros.Items.IndexOf(Arq_Dados.ListarColuna2());

var Coluna1 = Arq_Dados.BuscarColuna2(cmbNumeros.SelectedIndex);
txtNum.Text = Coluna1[0];

txt file:

460,089;        26;
711,07785;      32;
1014,5502       38;
1174,7475;      42;

Ex.: I select the number 26 in Combobox and he would have to return me the 460,089. But he is returning me the 711,07785.

  • You can’t understand what your code does. It’s better to [Dit] and post only the relevant part of the code.

  • @LINQ Ok, I will edit. It is that the rest of the code is to read the txt file and return me the values, and it is compiling right. Just this code that isn’t returning me to the right line. I just edited if you can help me, be very grateful!

  • @Would Jéfbueno help me? I think it’s a simple mistake, but I’m not finding.

  • Later today I’ll have a few minutes free and read the question slowly.

  • I just reread the question and tried to reproduce the problem locally and I couldn’t do it. With the information you passed on the question, the code works normally. My tip for you is: try to isolate the problem, remove all the unnecessary code to understand it (it’s even better to create new code to test). By doing this you will probably be able to solve the problem on your own, but if you cannot, you can [Dit] the question and leave a playable example.

  • @I’ll do that, thanks for the tip. I don’t know if this helps you, this question that I created came from another one that I had already done and the two connect. For this question is the complement of the other (https://answall.com/questions/509608/ler-um-arquivo-txt-inserir-em-um-array-e-mostrar-em-um-textbox-no-c)

Show 1 more comment

1 answer

0


The generated numDay values are going to the combobox, and there are other values already registered in the combobox (are same values in txt file)

The problem must be there. You are entering all the values of the file in the combobox and then adding more txt input (numDiam)?

It’s a bit foggy, I don’t know if you’re updating the file and loading it several times and etc. If you’re not adding items again in the combobox, this error wasn’t meant to happen.

Anyway, you can change the method BuscarColuna2 and make it search by value instead of index.

public string[] BuscarColuna2(string valor) {
    // Se quiser usar Linq...
    // return Dados.Where(d => d[1] == valor).FirstOrDefault();
    
    // tradicional.
    for (int i = 0; i < Dados.Count; i++) {
        if (Dados[i][1] == valor) {
            return Dados[i];
        }
    }
    
    return null;
}


// NO EVENTO DO COMBOBOX...
var coluna1 = Arq_Dados.BuscarColuna2(cmbNumeros.SelectedItem as string);
  • It worked! Thank you so much for your help!

Browser other questions tagged

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