Load two fields from a Datagrid using a txt file

Asked

Viewed 368 times

1

How can I do this, see what I have so far:

Datagrid, I need to load the comboBox and the valor unitário with values I previously saved on a txt

inserir a descrição da imagem aqui

Button save products, save name - price

private void btnGravar_Click(object sender, EventArgs e)
        {
            i++;
            double vtotal = 0;
            vtotal = Convert.ToDouble(txtVlrVenda.Text) * Convert.ToInt32(txtQntd.Text);

            dgvProdutos.Rows.Add(i, txtNome.Text, txtFornecedor.Text, maskCNPJ.Text, txtEnd.Text, txtCidade.Text, txtUF.Text, maskFone.Text, txtEmail.Text, txtNfe.Text, txtVlrVenda.Text, txtQntd.Text, vtotal);


            using (StreamWriter writer = new StreamWriter(@"C:\\Users\\willian\\Downloads\\dbProdutos.txt", true))
            {
                writer.WriteLine(txtNome.Text + " - " + txtVlrVenda.Text);
            }


            txtNome.Text = "";
            txtFornecedor.Text = "";
            maskCNPJ.Text = "";
            txtEnd.Text = "";
            txtCidade.Text = "";
            txtUF.Text = "";
            maskFone.Text = "";
            txtEmail.Text = "";
            txtNfe.Text = "";
            txtVlrVenda.Text = "";
            txtQntd.Text = "";

            btnEditar.Enabled = true;
            btnExcluir.Enabled = true;
            btnGravar.Enabled = false;
        }

In this previous topic: Save to txt and recover in a combobox taught me to carry comboBox, however in this case I did not understand how to access the column I created inside Datagrid. The code so far is like this:

private void frmOrdemServico_Load(object sender, EventArgs e)
        {


            string[] lineOfContents = File.ReadAllLines(@"C:\\Users\\willian\\Downloads\\dbClientes.txt");
            cbClientes.Items.Clear(); // limpar para não duplicar valores
            foreach (var line in lineOfContents)
            {
                string[] nomes = line.Split(',');
                cbClientes.Items.Add(nomes[0]);
            }


            string[] Produtos = File.ReadAllLines(@"C:\\Users\\willian\\Downloads\\dbProdutos.txt");
            foreach (var line in Produtos)
            {
                string[] produtos = line.Split('-');
                dgvProdutos. //comboBox que irá carregar os produtos
                dgvProdutos. //txtBox que irá mostrar o valor de cada produto seleciona, ja cadastrado no txt
            }
        }

Can anyone help me with something? I even found this site that teaches to recover values that are concatenated but to put in Datagrid does not say anything: Writing and Reading Data in Text File with Csharp

  • 1

    Question: why are you using a TXT for such complex operations?

  • Answer: Because I was using a database and I couldn’t, so it seems more viable this way txt, since I will only present to teachers and the subjects does not charge database at most using same text files. I just want to show there and good will not record anything else, just to show how the system works stream passes etc.

1 answer

1

One solution is to use a Datatable for the service.

Add to your project one Datatable with two columns, 'Product' and 'Price'

public DataTable produtos = new DataTable() { Columns = { new DataColumn { ColumnName = "Produto" }, new DataColumn { ColumnName = "Preço" } } };

fill this Datatable with the file data as follows:

public static void lerProdutos()
{
    DataGridViewComboBoxColumn comboBox = (DataGridViewComboBoxColumn)dataGridView.Columns[0];
    string[] Produtos = File.ReadAllLines(@"C:\\Users\\willian\\Downloads\\dbProdutos.txt");
    foreach (var line in Produtos)
    {
        string[] Dados = line.Split('-');
        produtos.Rows.Add(Dados[0], Dados[1]);
        comboBox.Items.Add(Dados[0]);
    }
}

In your Datagridview, Add the Event Editingcontrolshowing which will verify the value of the combobox was amended

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        if (dataGridView.CurrentCell.ColumnIndex == 1 && e.Control is ComboBox)
        {
            ComboBox comboBox = e.Control as ComboBox;
            comboBox.SelectedIndexChanged -= valorModificado;
            comboBox.SelectedIndexChanged += valorModificado;
        }
    }

and the event that will fetch the price of the product:

private void valorModificado(object sender, EventArgs e)
    {
        DataGridViewComboBoxColumn comboBox = (DataGridViewComboBoxColumn)dataGridView.Columns[0];

        DataRow[] rows = produtos.Select($"Produto = '{comboBox.ValueMember}'");
        string valor = rows[0][0].ToString();
        comboBox.ValueMember = rows[0][0].ToString();
    }

Browser other questions tagged

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