Error trying to write comboBox and MaskTextBox

0

I have a form with two fields:

  • 1 ComboBox that I put the type of people (Physique or Juridica);
  • 1 MaskTextBox with CPF;

AtfirstIdonotknowwhat'sbestifyousavethevalueoftheIndexofthecomboboxoritstext.BecausethenwhenIgosearchingIwillneedtoloadthiscomboboxagain.

Mybanklookslikethis:

CREATETABLECLIENTES(id_clienteSERIALPRIMARYKEYNOTNULL,tipoINT,tiposVARCHAR(10),CPFINT);

ImadeitverysimpletolearnandIlefttipos/tipototestbothways.

MyconnectionclassandmethodtoInsert:

classDAL{staticstringserverName="localhost";
        static string port = "5432";
        static string userName = "postgres";
        static string password = "adm";
        static string databaseName = "dbestoque";
        NpgsqlConnection conn = null;
        string ConnString = null;

        public DAL()
        {
            ConnString = String.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};",
                                       serverName, port, userName, password, databaseName);

        }
 public void InserirClientes(int cb, int cpf)
        {
            using (conn = new NpgsqlConnection(ConnString))
            {
                conn.Open();
                string cmdInserir = String.Format("INSERT INTO CLIENTES(tipo, cpf) VALUES ('{0}', '{1}')", cb, cpf);

                using (NpgsqlCommand cmd = new NpgsqlCommand(cmdInserir, conn))
                {
                    cmd.ExecuteNonQuery();
                }
            }
        }

Record button:

private void btnGravar_Click(object sender, EventArgs e)
    {
        DAL n = new DAL();
        try
        {
            n.InserirClientes(cbTipo.SelectedIndex, Convert.ToInt16(mskCPF.Text));
        }catch(Exception ex)
        {
            throw ex;
        }
        finally
        {
            MessageBox.Show("Efetuado");
        }

    }

Error:

System.FormatException ocorrido
  HResult=0x80131537
  Message=A cadeia de caracteres de entrada não estava em um formato correto.
  Source=ProjetoAlpha
  StackTrace:
   em ProjetoAlpha.frmCadastros.btnGravar_Click(Object sender, EventArgs e) em C:\Users\willian\source\repos\ProjetoAlpha\ProjetoAlpha\frmCadastros.cs:linha 28
   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
    
asked by anonymous 18.10.2017 / 20:49

2 answers

0

Some points to change:

1 - I would change the control, instead of a comboBox, I would use a radioBox, it will be simpler and you will only store a boolean:

2 - Change the CPF data type, which can also be CNPJ. A variable integer only goes to +2147483647, with this, will always give error by the size of cpf / cnpj. I would use VarChar (18) and would already write to the mask.

3 - Use NpgsqlParameter to pass the parameters to the command, it is correct even for security reasons.

I have no example of Npgsql here, but as soon as I can, I can change the answer.

  

Note: The current error occurs at the following point: Convert.ToInt16(mskCPF.Text) .    If I tried to put Int64 it would still pass, but it would give error in postgres. Int32 no longer fits a CPF, Int16 then ...

I hope it helps.

    
18.10.2017 / 21:37
0

There is a different way you can save the client type:

  • Change the "type" field of the database, from INT to VARCHAR

  • Assign the text of the ComboBox to a String, and then save it to the database.

I also had this doubt in an application that I developed in VB, and I decided that way.

Below is an example of the application (made in VB):

    Dim sexo As String
    sexo = cbosexocli.Text.ToUpper.First

    comando.CommandText = ("insert into clientes(codcli, nomecli, salariocli, sexocli, nascimento) values(" & txtcodcli.Text & ",'" & txtnomecli.Text & "'," & txtsalariocli.Text & ",'" & sexo & "',CONVERT(datetime,'" & msknascimentocli.Text & "',103))")
    
18.10.2017 / 21:14