I am new to C#. I am trying to save the numbers into a SQL Server database table (locally) but I get an error:
Cannot insert the value NULL into column
My code:
private void SaveBtn_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\fn1965\Desktop\Work\TESTDB\NumDB.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
string insert_query = "INSERT into [NumericTable] (Num1, Num2, Total) VALUES (@Num1, @Num2, @Total)";
SqlCommand cmd = new SqlCommand(insert_query, conn);
cmd.Parameters.AddWithValue("@Num1", textBox1.Text);
cmd.Parameters.AddWithValue("@Num2", textBox2.Text);
cmd.Parameters.AddWithValue("@Total", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Record saved");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("EROR:"+ ex.ToString());
}
}
Table schema


NULLSnvarchar(50)?? Use the most appropriate datatype - always, no exceptions. Andnvarchar(50)is certainly NOT the most appropriate datatype to store numerical values! Useint,bigint, ordecimal- whatever suits your needs