Hello Friends,
I am a beginner in ADO.net. I have a simple form with three text field and a submit button. Now i am trying to enter the text field values into database. I have database name: "ashish" with a table name "ashish1". Now what i did, i created a connection through wizard. And that connection generate a connection string "Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\Data\ashish.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True". And on botton event i am entering this code:
private void button1_Click(object sender, EventArgs e)
{
try
{
/*SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SQLEXPRESS;Initial Catalog=ashish;Integrated Security=True;Connect Timeout=30;User Instance=True";
con.Open();*/
string quary = "insert into ashish1(name, address, phone) values(@name, @address, @phone)";
SqlCommand cmd= new SqlCommand();
cmd.CommandText = quary;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@name", textBox1.Text.ToString());
cmd.Parameters.AddWithValue("@address", textBox2.Text.ToString());
cmd.Parameters.AddWithValue("@phone", textBox3.Text.ToString());
cmd.ExecuteNonQuery();
}
catch (Exception ed)
{
MessageBox.Show(ed.ToString());
}
}
Now when i click upon submit button, system is showing me an error. Error message is:
System.InvalidOperationExection: ExecuteNonQuery: Connection property has not been initialized.
at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at WindowsApplication1.form2.button1_click(...) in ..\form2.cs
Please guys guide me how do i insert the data.
Thanks,
Ashish
Bookmarks