Reputation: 1
cmd.executenonquery showing (can't have null values) ERROR!
Here is the code behind
I am trying to insert data into textboxes and sent to a table in a database, but it keeps showing NULL.
SqlConnection con = new SqlConnection("Data Source=*******;Initial Catalog=MaleFemale;Integrated Security=True");
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (con.State == System.Data.ConnectionState.Closed)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into TableMaleFemale(Name,EiD,Gender) values ('" + NametextBox.Text + "', '" + EiDtextBox.Text + "', '" + GendertextBox.Text + "')", con);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
}
Upvotes: 0
Views: 57
Reputation: 152644
There are three things that you should change with your code:
using
statement blocksIf I make those changes, your code is not more like this:
String connectionString = "Data Source=*******;Initial Catalog=MaleFemale;Integrated Security=True";
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = "insert into TableMaleFemale(Name,EiD,Gender) values (@Name, @EiD, @Gender)"
using(SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("@Name").Value = NametextBox.Text == null ? DBNull.Value : NametextBox.Text;
cmd.Parameters.Add("@EiD").Value = EiDtextBox.Text == null ? DBNull.Value : EiDtextBox.Text;
cmd.Parameters.Add("@Gender").Value = GendertextBox.Text == null ? DBNull.Value : GendertextBox.Text;
connection.Open();
cmd.ExecuteNonQuery();
}
con.Close();
}
}
None of these three things may fix your stated problem, but it will solve other problems that you don't have yet.
Upvotes: 2