Error trying to save combobox and Masktextbox

Asked

Viewed 77 times

0

I have a form with two fields:

  • 1 Combobox I put the type of people (Physics or Legal);
  • 1 Masktextbox with CPF;

inserir a descrição da imagem aqui

At first I don’t know what’s better if I keep the value of Index of the combobox or its text. Because after that I will need to load this combobox again.

My bank is like this:

CREATE TABLE CLIENTES(
    id_cliente SERIAL PRIMARY KEY NOT NULL,
    tipo INT,
    tipos VARCHAR(10),
    CPF INT
);

I made it very simple to learn and left the tipos/tipo to test the two forms.

My connection class and the method to Insert:

class DAL
    {
        static string serverName = "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

2 answers

0

There is a different way that you can save the customer type:

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

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

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

Below is an example of the application (done 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))")
  • only use TEXT for very large fields, and which do not require a search, the normal is VARCHAR

  • Thanks for the tip Rovann ! I already changed this in my comment.

0

Some points to change:

1- I would change the control, instead of a combobox, I would use a radioBox, it is simpler and you only store a Boolean:

inserir a descrição da imagem aqui

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

3- Utilize 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 change the answer.

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

I hope it helps.

Browser other questions tagged

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