In my program I have two text input fields (in windows form) and a button to add/save those values into the DB table. The problem is once I click the button, it does not insert the inputs into the DB, instead it shows the error I have attached below as image.
What is wrong with my program?
My working code:
public partial class Form1 : Form
{
//original Connection string is exactly the following:
//Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\Sanad Al Nahaj\Documents\thesaurus.mdf";Integrated Security=True;Connect Timeout=30
SqlConnection conn = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename=C:\Users\Sanad Al Nahaj\Documents\thesaurus.mdf;Integrated Security = True; Connect Timeout = 30");
public Form1()
{
InitializeComponent();
}
//Save button
private void button1_Click(object sender, EventArgs e)
{
conn.Open();//error pops up here after clicking the button
SqlCommand command = conn.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = "insert into Table values('"+wordbox.Text+"','"+synonymbox.Text+"')";
command.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Word and Synonym added!");
}
private void display_Click(object sender, EventArgs e)
{
//implement
}
}
Error:
Database looks like:
UPDATE:
My modification in Using
pattern (referring to CDove's answer):
var command = new SqlCommand();
using (command = new SqlCommand(
"insert into......)
))