Write data to the database (Value Member and Display Member)

Asked

Viewed 439 times

3

I am having trouble writing this data into the database (Postgresql). In case the data you would like to save is: Customer Name Origin, Customer Name Destination, Order Date, Payment Date, Confirm Payment, Payment Method and the Total label.

But when I click on include tell me an error. Follow what I already have and the respective screens and codes:

Imagem do formulário

Imagem do erro ao tentar incluir

Form class "Customer request"

 class solicitacaocliente
{
    banco conexao = new banco();

    private int clienteOrigem; //Nome do cliente Origem
    private int clienteDestino; // Nome do cliente destino
    private DateTime DataSolicitacao; // Data que foi solicitado os produtos
    private DateTime DataPagamento; // Data que foi efetuado o pagamento
    private string CbPago; // Confirmar se foi pago (Confirmar pagamento)
   // private int cod; // 
    private double vTotal; // Valor total dos produtos escolhidos
   // private int qntd; // Qntd de cada produto escolhido
  //  private int idProduto; // Código de cada produto
    private int formpgto; // Tipo de pagamento ( a vista, a prazo ...)


    public solicitacaocliente(int pCliO, int pCliD, DateTime pDataSol, DateTime pDataPgto, string pPago, int pFrmpgto, double pTotal)
    {
        clienteOrigem = pCliO;
        clienteDestino = pCliD;
        DataSolicitacao = pDataSol;
        DataPagamento = pDataPgto;
        CbPago = pPago;
        formpgto = pFrmpgto;
        vTotal = pTotal;

}

    public solicitacaocliente()
    {


    }

    public void IncluirSolicitacao()
    {
        NpgsqlCommand cmd = new NpgsqlCommand();
        cmd.Connection = conexao.conecta(); // Instacia o metodo conecta() que está na classe BANCO
        cmd.CommandText = "Insert into solicitacao_cliente (data_pedido, data_pagamento, valor_total, cliente_o, cliente_d, pago, cod_formapgto) values (@data_pedido, @data_pagamento, @valor_total, @cliente_o, @cliente_d, @pago, @cod_formapgto)";
        cmd.Parameters.Add(new NpgsqlParameter("@data_pedido", DataSolicitacao)); // atributo e campo declarado banco de dados.
        cmd.Parameters.Add(new NpgsqlParameter("@data_pagamento", DataPagamento));
        cmd.Parameters.Add(new NpgsqlParameter("@valor_total", vTotal));
        cmd.Parameters.Add(new NpgsqlParameter("@cliente_o", clienteOrigem));
        cmd.Parameters.Add(new NpgsqlParameter("@cliente_d", clienteDestino));
        cmd.Parameters.Add(new NpgsqlParameter("@pago", CbPago));
        cmd.Parameters.Add(new NpgsqlParameter("@cod_formapgto", formpgto));

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

Method to load Combobox with database information

public ComboBox IniciaLoad(string ptabela, string pexibe, string pvalor, ComboBox cmbres)
    {
        banco conexao = new banco();
        NpgsqlCommand cmd = new NpgsqlCommand();
        cmd.Connection = conexao.conecta();
        cmd.CommandText = "select " + pvalor + "," + pexibe + " from " + ptabela; // Esse terei que passar.

        try
        {
            NpgsqlDataReader ler = cmd.ExecuteReader();
            DataTable dt = new DataTable();

            dt.Columns.Add(pvalor, typeof(int)); //Código
            dt.Columns.Add(pexibe, typeof(string)); //Nome
            dt.Load(ler);


            cmbres.DisplayMember = pexibe; // cmbOnde valor vai
            cmbres.ValueMember = pvalor;
            cmbres.DataSource = dt;

            ler.Close();
            ler.Dispose();
            return cmbres;


        }
        catch (Exception)
        {
            return cmbres;
        }

        conexao.desconecta(cmd.Connection);
    }

LOAD event form "Customer request"

private void frmSolicitacaoCliente_Load(object sender, EventArgs e)
    {
        datagride ngrid = new datagride(dgvSolicitacaoCliente);
        ngrid.CarregarProdutos(); // Carregar DataGridView dos produtos.

        solicitacaocliente sc = new solicitacaocliente();
        cmbcliDestino = sc.IniciaLoad("CLIENTE", "NOME", "COD_CLIENTE", cmbcliDestino);
        cmbcliOrigem = sc.IniciaLoad("CLIENTE", "NOME", "COD_CLIENTE", cmbcliOrigem);
        cmbFormaPgto = sc.IniciaLoad("FORMA_PAGAMENTO", "NOME", "COD_FORMAPGTO", cmbFormaPgto);

    }

Code implemented in the INCLUDE button of the form "Customer Request"

private void btnIncluir_Click(object sender, EventArgs e)
    {
        try {
            solicitacaocliente guardar = new solicitacaocliente(Convert.ToInt32(cmbcliOrigem.SelectedValue.ToString()), Convert.ToInt32(cmbcliDestino.SelectedValue.ToString()), Convert.ToDateTime(dtpDataSolicitacao.Text), Convert.ToDateTime(dtpPagamento.Text), cmbPago.SelectedValue.ToString(), Convert.ToInt32(cmbFormaPgto.SelectedValue.ToString()), Convert.ToDouble(lblValorTotal.Text));
            guardar.IncluirSolicitacao();
            MessageBox.Show("Incluso com sucesso!");
        }
        catch (Exception ex) // Caso de erro, irá mostrar a mensagem de erro!
        {
            MessageBox.Show(ex.ToString()); // mensagem de erro
        }
    }

Note that may be relevant: In the error code it is on line 58 which is exactly the line of the button include, when I am passing the parameters.

Error message

System.NullReferenceException was unhandled
  HResult=-2147467261
  Message=Referência de objeto não definida para uma instância de um objeto.
  Source=Vendas Diretas Versao Atualizada
  StackTrace:
       em Vendas_Diretas_Versao_Atualizada.frmSolicitacaoCliente.btnIncluir_Click(Object sender, EventArgs e) na C:\Users\WILL\Documents\Visual Studio 2013\Projects\Vendas Diretas Versao Atualizada\Vendas Diretas Versao Atualizada\Solicitacao Cliente.cs:linha 58
       em System.Windows.Forms.Control.OnClick(EventArgs e)
       em System.Windows.Forms.Button.OnClick(EventArgs e)
       em System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       em System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       em System.Windows.Forms.Control.WndProc(Message& m)
       em System.Windows.Forms.ButtonBase.WndProc(Message& m)
       em System.Windows.Forms.Button.WndProc(Message& m)
       em System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       em System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       em System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       em System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       em System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       em System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       em System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       em System.Windows.Forms.Application.RunDialog(Form form)
       em System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
       em System.Windows.Forms.Form.ShowDialog()
       em Vendas_Diretas_Versao_Atualizada.frmPrincipal.clientesToolStripMenuItem1_Click(Object sender, EventArgs e) na C:\Users\WILL\Documents\Visual Studio 2013\Projects\Vendas Diretas Versao Atualizada\Vendas Diretas Versao Atualizada\Principal.cs:linha 83
       em System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
       em System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
       em System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
       em System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
       em System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
       em System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
       em System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
       em System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
       em System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       em System.Windows.Forms.Control.WndProc(Message& m)
       em System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       em System.Windows.Forms.ToolStrip.WndProc(Message& m)
       em System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
       em System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       em System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       em System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       em System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       em System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       em System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       em System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       em System.Windows.Forms.Application.Run(Form mainForm)
       em Vendas_Diretas_Versao_Atualizada.Program.Main() na C:\Users\WILL\Documents\Visual Studio 2013\Projects\Vendas Diretas Versao Atualizada\Vendas Diretas Versao Atualizada\Program.cs:linha 19
       em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       em System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
  • Willian, instead of putting a print of the error message you can copy the error text and put in the question?

  • But the message you give me is the one I posted, is it bad enough to read? It’s just that in the Messagebox that appears, you can’t copy the text, but if you have to, I’ll write without problems

  • No no. I’m telling you the message that appears to you in Visual Studio. It’s definitely different from this message from MessageBox

  • So, just give me this mistake really, is it because I did the treatment with try and catch? I’ll take it off to see what it shows

  • 1

    Ah, absolutely. This "treatment" of yours doesn’t help at all. You should do a search about exceptions here on the site, there are several things to help you...

  • Then the error message used the copy exception detail for clipboard, is enough so I put what I think should be relevant, see if it is enough. Thanks I put everything together

Show 1 more comment

2 answers

1

At a conversion error when creating the requested instance, one of your fields is null.

Create a variable for each field and debug to find which field is null.

0


Just so I can close this question the friend @jbueno helped me with the mistake.

The problem was in this part of the code.:

solicitacaocliente guardar = new solicitacaocliente(Convert.ToInt32(cmbcliOrigem.SelectedValue.ToString()), Convert.ToInt32(cmbcliDestino.SelectedValue.ToString()), Convert.ToDateTime(dtpDataSolicitacao.Text), Convert.ToDateTime(dtpPagamento.Text), cmbPago.SelectedValue.ToString(), Convert.ToInt32(cmbFormaPgto.SelectedValue.ToString()), Convert.ToDouble(lblValorTotal.Text));

I was instructed to remove the .ToString() and pass the values on variables because some of them are receiving NULL.

The correct code looked like this:

private void btnIncluir_Click(object sender, EventArgs e )
    {
        banco conexao = new banco();
        NpgsqlCommand cmd = new NpgsqlCommand();
        cmd.Connection = conexao.conecta();

       try {

        int origem = Convert.ToInt32(cmbcliOrigem.SelectedValue);
        int destino = Convert.ToInt32(cmbcliDestino.SelectedValue);
        DateTime HoraPedido = Convert.ToDateTime(dtpDataSolicitacao.Text);
        DateTime HoraPagamento = Convert.ToDateTime(dtpPagamento.Text);
        string PagoOuAberto = cmbPago.SelectedItem.ToString(); 
        int FormaDePagamento = Convert.ToInt32(cmbFormaPgto.SelectedValue);
        double ValorTotal = Convert.ToDouble(lblValorTotal.Text);

            solicitacaocliente guardar = new solicitacaocliente(origem, destino, HoraPedido, HoraPagamento, PagoOuAberto, FormaDePagamento, ValorTotal);
            lblNumSolicitacao.Text = guardar.IncluirSolicitacao();

       }
         catch (Exception ex) // Caso de erro, irá mostrar a mensagem de erro!
       {
           MessageBox.Show(ex.ToString()); // mensagem de erro
       }

Browser other questions tagged

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