Error writing in SQL table from Windowsform

Asked

Viewed 24 times

0

I’m trying to write several fields in a table from a Windows Form App. Some of these fields are Foreign Keys from other tables. If the fields have values, the SQL statement is executed but if they do not have values I get a conversion error (Text to Int).

    SqlCommand comando = new SqlCommand("insert into tb_imagem (imagem,nome_imagem,descr_imagem,ND,iddiag,idlesao,idlesao1,idlesao2,idlesao3,idlesao4) values (@imagem,@nome_imagem,@descr_imagem,@ND,@iddiag,@idlesao,@idlesao1,@idlesao2,@idlesao3,@idlesao4)", con);
    SqlCommand cmdInteiro = new SqlCommand(sql, con);

    SqlParameter imagem = new SqlParameter("@imagem", SqlDbType.VarBinary);
    SqlParameter nome_imagem = new SqlParameter("@nome_imagem", SqlDbType.VarChar);
    SqlParameter descr_imagem = new SqlParameter("@descr_imagem", SqlDbType.VarChar);
    SqlParameter ND = new SqlParameter("@ND", SqlDbType.Int);
    SqlParameter iddiag = new SqlParameter("@iddiag", SqlDbType.Int);
    SqlParameter idlesao = new SqlParameter("@idlesao", SqlDbType.Int);
    SqlParameter idlesao1 = new SqlParameter("@idlesao1", SqlDbType.Int);
    SqlParameter idlesao2 = new SqlParameter("@idlesao2", SqlDbType.Int);
    SqlParameter idlesao3 = new SqlParameter("@idlesao3", SqlDbType.Int);
    SqlParameter idlesao4 = new SqlParameter("@idlesao4", SqlDbType.Int);

    imagem.Value = foto;
    nome_imagem.Value = TextBoxNomeImagem.Text;
    descr_imagem.Value = TextBoxDescrImagem.Text;
    iddiag.Value = TextBoxiddiag.Text;
    idlesao.Value = TextBoxidlesao.Text;
    idlesao1.Value = TextBoxidlesao1.Text;
    idlesao2.Value = TextBoxidlesao2.Text;
    idlesao3.Value = TextBoxidlesao3.Text;
    idlesao4.Value = TextBoxidlesao4.Text;
    ND.Value = TextBoxND.Text);

Any idea what might be going on and how to fix it?

Thank you Hadrian

  • This must be happening because the field is empty (null) and when trying to convert can not. Adriano, you checked this possibility?

1 answer

0

The exception is of the type ArgumentNullException, for the SqlParameter makes an internal conversion using the System.Int32.Parse(string) to collect property data parametro.Value. If value is null (which would be an empty textbox.text) the exception is thrown To get a zero return use:

parametro.Value = Convert.ToInt32(seusTextBoxidlesao.Text);

Or else you can use the method AddWithParameter(); following example below:

inserir a descrição da imagem aqui

With this method I believe you will not get any problem.

  • Thank you very much Paulo Ricardo. His second option worked well.

  • thanks for the return @Adriano. if it was useful for you, signals the answer to give a moral right?

  • Paulo Ricardo, I signaled but as I have reputation < 15 (Newbie) does not appear.

Browser other questions tagged

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