Problem writing data to Postgres

Asked

Viewed 658 times

2

I have two tables in postgres (PRODUCT and CATEGORY)

In the PRODUCT table I have the FIELDS -> ID, product name, description, value, Id_categoria.

In the CATEGORY table I have the FIELDS -> Id_category and Category.

In my Visual Studio project, I created a form to record new categories. Informing only an ex NAME. (Perfume, Accessories etc).

And I also have a form for registration of PRODUCTS where it is necessary to inform the product name, description, value and select a category code that fits (choose on combobox)

My problem is now: I cannot save the PRODUCT form because COMBOBOX is related to the CATEGORY NAME, because the person needs to know what will select and not see the codes. And in POSTGRES the field is INTEGER (Id_category), so it does not save the NAME.

PRODUCT form LOAD event. (old)

 private void CadastroProduto_Load(object sender, EventArgs e)
    {
        banco conexao = new banco(); // Classe de conexão.

        // Como carregar dados que estão no PostgreSQL no ComboBox

        NpgsqlCommand cmd = new NpgsqlCommand();
        cmd.Connection = conexao.conecta(); // Abre conexão
        cmd.CommandText = "Select * from categoria"; // Seleciona a tabela
        cmd.ExecuteNonQuery(); // Executa a busca
        try
        {
            NpgsqlDataReader ler = cmd.ExecuteReader(); ; // Leitura de dados

            while (ler.Read()) // Enquanto tiver campos para ler 
            {
                cmbCategoriaProduto.Items.Add(ler["nome"]); 
            }
            ler.Close();
            ler.Dispose();

        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        conexao.desconecta();
    }

Updated FORM LOAD event (Updated: 05/10):

private void CadastroProduto_Load(object sender, EventArgs e)
    {
        banco conexao = new banco(); // Classe de conexão.

        // Como carregar dados que estão no PostgreSQL no ComboBox

        NpgsqlCommand cmd = new NpgsqlCommand();
        cmd.Connection = conexao.conecta(); // Abre conexão
        cmd.CommandText = "Select cod_categoria, nome from categoria"; // Seleciona a tabela
        cmd.ExecuteNonQuery(); // Executa a busca
        try
        {
            NpgsqlDataReader ler = cmd.ExecuteReader(); ; // Leitura de dados
            DataTable dt = new DataTable();

            dt.Columns.Add("cod_categoria", typeof(string));
            dt.Columns.Add("nome", typeof(string));
            dt.Load(ler);

            cmbCategoriaProduto.DisplayMember = "nome";
            cmbCategoriaProduto.ValueMember = "cod_categoria";
            cmbCategoriaProduto.DataSource = dt;
           // while (ler.Read()) // Enquanto tiver campos para ler 
           //{
           //     cmbCategoriaProduto.Items.Add(ler["nome"]); 
           // }
            ler.Close();
            ler.Dispose();

        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        conexao.desconecta();
    }

Combobox Selectedindex Event

private void cmbCategoriaProduto_SelectedIndexChanged(object sender, EventArgs e)
    {
        string id = cmbCategoriaProduto.SelectedValue.ToString();
    }

Still Error While Saving: Error:

inserir a descrição da imagem aqui

Attributes and methods

// Atribulos
    private string Nome;
    private string Descricao;
    private double Valor;
    private string cCategoria;

    //metodo construtor
    public produto(string pn, string pd, double pv, string pccat)
    {
        Nome = pn;
        Descricao = pd;
        cCategoria = pccat;
        Valor = pv;

    }

Product Class - Include Method();

public void IncluirProduto()
    {
        NpgsqlCommand cmd = new NpgsqlCommand();
        cmd.Connection = conexao.conecta(); // Instacia o metodo conecta() que está na classe BANCO
        cmd.CommandText = "Insert into produto (nome, descricao, cod_categoria, valor) values(@nome,@descricao,@cod_categoria,@valor)";
        cmd.Parameters.Add(new NpgsqlParameter("@nome", Nome)); // atributo e campo declarado banco de dados.
        cmd.Parameters.Add(new NpgsqlParameter("@descricao", Descricao));
        cmd.Parameters.Add(new NpgsqlParameter("@cod_categoria", cCategoria));
        cmd.Parameters.Add(new NpgsqlParameter("@valor", Valor));

        cmd.ExecuteNonQuery();
        conexao.desconecta(); // instancia o metodo desconecta() que está na classe BANCO
    }

Sign Up Button

private void btnCadastrarProduto_Click(object sender, EventArgs e)
    {
        try
        {
            produto pdt = new produto(txtNomeProduto.Text, txtDescricaoProduto.Text, Convert.ToDouble(txtValorProduto.Text),cmbCategoriaProduto.Text);
            pdt.IncluirProduto();
            MessageBox.Show("Produto Incluso com sucesso!");        
        }
        catch (Exception ex)    
        {
            MessageBox.Show(ex.ToString());
        }
    }
  • 2

    Give a read on your question, this confused medium. I could not understand right what the problem and what would be the expected result. The code you posted doesn’t seem to have anything to do with your doubt.

  • See if it’s clearer @Christianberegula

  • I’ll give you a hint, the code you had in the question has some robustness issues but it has nothing to do with your problem. And I don’t think the problem is so clear yet. Is it an SQL only problem? Case of picking foreign key?

  • @Sorry it took me so long to get back to you. So I applied exactly how the msdn website does, even so qnd will record the error.

  • What error appears? this Selectedindexchanged event is just that? if the error is there, updating the id as a local variable. You can post the SAVE event?

  • @Christianberegula put the photo of the error that, basically is that the field has to record int, but I do not know where else

  • The code of the button REGISTER, put it. the error is certainly there.

  • @Christianberegula I updated

  • the error is here -> cmbCategoriaProduto.Text where you create the new product

  • I don’t know what else to do. I have to convert to int. I’ve tried but Formatexception error

Show 5 more comments

2 answers

3

You could use a Dictionary when loading your combobox.

Dictionary<string, int> options = new Dictionary<string, int>();

//função que você chama para carregar seu combobox
//dentro do loop de leitura do banco de dados
options.Add(nomeCategoria, ID_categoria);

Now where you call Save from your form, you just need to recover the id equivalent to the category name.

int idDesejado;
options.TryGetValue(nomeSelecionado, out idDesejado)
  • I’ll try this form. I’ll tell you what happened. Thanks

1


From what I could understand,

you are filling out the combobox using a database query and in that query you get only the category name. The product table has only the category identifier.

If this is the problem, it can be solved in the following ways:

First solution, in this question the situation is similar. What you can do is that the query to fill the combobox has the two columns, identifier and category name, and use the property Valuemember for the column Id_categoria and the property Displaymember for the column headform. As shown in the example of question.

Second solution, if the category names do not repeat in the table, do a new search for the name of the category selected in the category table looking for the identifier and fill in the products table (I don’t like the idea).

  • That’s right @Filipe, I will put the code where I load the combobox - Load event of the Product form. If you can take a look

  • Exactly! You can apply the solution of the question I presented, or the solution of @Christianberegula, which is also excellent.

Browser other questions tagged

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