ExecuteReader: Connection property has not been initialized.
my coding is
protected void Button2_Click(object sender,
you have to assign connection to your command object, like..
SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"')");
cmd.Connection = conn;
You can also write this:
SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (@project, @iteration)", conn);
cmd.Parameters.AddWithValue("@project",name1.SelectedValue);
cmd.Parameters.AddWithValue("@iteration",iteration.SelectedValue);
All of the answers is true.This is another way. And I like this One
SqlCommand cmd = conn.CreateCommand()
you must notice that strings concat have a sql injection problem. Use the Parameters http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
After SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('....
Add
cmd.Connection = conn;
Hope this help
I like to place all my sql connections in using
statements. I think they look cleaner, and they clean up after themselves when your done with them. I also recommend parameterizing every query, not only is it much safer but it is easier to maintain if you need to come back and make changes.
// create/open connection
using (SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=rags;Integrated Security=SSPI")
{
try
{
conn.Open();
// initialize command
using (SqlCommand cmd = conn.CreateCommand())
{
// generate query with parameters
with cmd
{
.CommandType = CommandType.Text;
.CommandText = "insert into time(project,iteration) values(@name, @iteration)";
.Parameters.Add(new SqlParameter("@name", this.name1.SelectedValue));
.Parameters.Add(new SqlParameter("@iteration", this.iteration.SelectedValue));
.ExecuteNonQuery();
}
}
}
catch (Exception)
{
//throw;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
{
conn.Close;
}
}
}
use this and pass connection object :
SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"')",conn);