Error writing to SQL table from WindowsForm

0

I am trying to write to a table several fields of a Windows Form App. Some of these fields are foreign keys from other tables. If the fields have values, the SQL statement executes 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 of what might be going on and how to solve it?

Thank you Adriano

    
asked by anonymous 20.01.2018 / 20:32

1 answer

0

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

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

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

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

    
21.01.2018 / 00:25