How to write a DateTimePicker to the database

-1

Hello,

I have a form with DateTimePicker - Short (date only).

And in the database I put DataEntrada DATE

My problem is, I created an insert method but I do not know how to pass the DateTimePicker by parameter.

Method of inserting records:

public void InserirRegistros(string nome, int codigo, int minimo, int maximo, int qtd, DateTime data)
{
    try
    {
        using (NpgsqlConnection conn = new NpgsqlConnection(ConnString))
        {
            conn.Open();

            string cmdInserir = String.Format("INSERT INTO ESTOQUE(codigo,codigo,minimo,maximo,quantidade,dataEntrada) " +
                                                            "VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", nome, codigo, minimo, maximo, qtd, data);

            using (NpgsqlCommand cmd = new NpgsqlCommand(cmdInserir, conn))
            {
                cmd.ExecuteNonQuery();
            }
        }
    }catch(NpgsqlException ex)
    {
        throw ex;
    }catch(Exception ex)
    {
        throw ex;
    }
    finally
    {
        conn.Close();
    }
}

Button Click event:

private void button1_Click(object sender, EventArgs e)
{
    DAL acesso = new DAL();

    try
    {
        acesso.InserirRegistros(txtNomeProduto.Text, Convert.ToInt32(txtCodigo.Text), Convert.ToInt32(txtMinimo.Text), Convert.ToInt32(txtMaximo.Text), Convert.ToInt32(txtEntrada.Text), Convert.ToDateTime(dtpData.DataBindings));
    }catch(Exception ex)
    {
        throw ex;
    }
    finally
    {
        MessageBox.Show("Cadastrado com sucesso!");
    }
}

Error:

System.InvalidCastException ocorrido
  HResult=0x80004002
  Message=Não é possível converter um objeto do tipo 'System.Windows.Forms.ControlBindingsCollection' no tipo 'System.IConvertible'.
  Source=ProjetoAlpha
  StackTrace:
   em ProjetoAlpha.frmProduto.button1_Click(Object sender, EventArgs e) em C:\Users\willian\source\repos\ProjetoAlpha\ProjetoAlpha\frmProduto.cs:linha 29
   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.Run(Form mainForm)
   em ProjetoAlpha.Program.Main() em C:\Users\willian\source\repos\ProjetoAlpha\ProjetoAlpha\Program.cs:linha 19

So far I have not been able to, because the field in the table is DATE (2010-01-01) and I'm passing in the wrong format, how do I arrange this? Do I need to change the parameter type to string?

    
asked by anonymous 11.10.2017 / 21:44

2 answers

0

Just change Convert.ToDateTime(dtpData.DataBindings) to dtpData.Value

Except for a mistake, if the field is of type Date and you enter a datetime in the parameters you will not have problems.

But anyway, you can use other values:

dtpData.Value.Date It remains a DateTime in C #, but with the time zeroed (01/01/2017 00:00:00)

Let's get one thing straight: Do not use string concatenation to mount the SQL command. See:

  

Your query has 2 columns, and it only has 6 columns, but you enter 7 parameters in the format string.

 using (NpgsqlConnection conn = new NpgsqlConnection(ConnString))
 {
        conn.Open();

        string cmdInserir = "INSERT INTO ESTOQUE(codigo,nome,minimo,maximo,quantidade,dataEntrada) VALUES (:codigo,:nome,:minimo,:maximo,:quantidade,:dataEntrada);";

        using (NpgsqlCommand cmd = new NpgsqlCommand(cmdInserir, conn))
        {
            NpgsqlParameter[] param = new  NpgsqlParameter[6];
            param[0] = new NpgsqlParameter("codigo", codigo);
            param[1] = new NpgsqlParameter("nome", nome);
            param[2] = new NpgsqlParameter("minimo", minimo);
            param[3] = new NpgsqlParameter("maximo", maximo);
            param[4] = new NpgsqlParameter("quantidade", quantidade);
            param[5] = new NpgsqlParameter("dataEntrada", data);
            cmd.Parameters.AddRange(param);
            cmd.ExecuteNonQuery();
        }
}
    
11.10.2017 / 22:12
0

The way to get the date selected in DateTimePicker is as follows:

private void button1_Click(object sender, System.EventArgs e)
{
   var dataSelecionada = dateTimePicker1.Value;
}

This will return you an object of type DateTime so you can move on to your method.

Documentation

    
11.10.2017 / 21:58