0

I am using asp.net with c# and there exist an error in these line of codes.

protected void btnsubmit_Click(object sender, EventArgs e)
{
    string type = "c";
    string FID = Session["FID"].ToString();
    SqlConnection cn = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    //int str_diff = Convert.ToInt32(ConfigurationManager.AppSettings["Difference"]);
    cn.ConnectionString = @"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True";
    cn.Open();
    cmd.CommandText = "update TrackingFaculty_det SET Type=@Type WHERE (FID=@FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60";
    cmd.Parameters.Add("@FID",SqlDbType.VarChar,10);
    cmd.Parameters["@FID"].Value = FID;
    cmd.Parameters.Add("@Type", SqlDbType.VarChar, 1);
    cmd.Parameters["@Type"].Value = type;
    cmd.ExecuteNonQuery();
    cn.Close();

    Response.Redirect("~/Faculty/Personaldet.aspx");
}

Error!!!

4
  • what error you are getting and on which line Commented Oct 7, 2013 at 5:31
  • i shown the error in the image attached itself Commented Oct 7, 2013 at 5:32
  • have you tried updating directly from sql server? Commented Oct 7, 2013 at 5:33
  • Yes @Nisha i have tried updating directly Commented Oct 7, 2013 at 5:36

3 Answers 3

4

You haven't set the connection to the command

cmd.Connection = cn;
Sign up to request clarification or add additional context in comments.

Comments

2

You need to assign the SqlConnection to the SqlCommand. As an additional suggestion I would wrap the connection in a using block to ensure it is correctly disposed in the case of an exception.

using (SqlConnection cn = new SqlConnection(@"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True") 
{
    cn.Open();
    SqlCommand cmd = new SqlCommand("update TrackingFaculty_det SET Type=@Type WHERE (FID=@FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60", cn);
    cmd.Parameters.Add("@FID",SqlDbType.VarChar,10);
    cmd.Parameters["@FID"].Value = FID;
    cmd.Parameters.Add("@Type", SqlDbType.VarChar, 1);
    cmd.Parameters["@Type"].Value = type;
    cmd.ExecuteNonQuery();
}

1 Comment

And if you're wrapping - then you should also wrap the SqlCommand in a using() { ... } block to ensure its proper disposal
0
    SqlCommand cmd = new SqlCommand("update TrackingFaculty_det SET Type=@Type WHERE (FID=@FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60", cn);
    cmd.Parameters.Add("@FID",SqlDbType.VarChar,10);
    cmd.Parameters["@FID"].Value = FID;
    cmd.Parameters.Add("@Type", SqlDbType.VarChar, 1);
    cmd.Parameters["@Type"].Value = type;
    cmd.ExecuteNonQuery();                       

3 Comments

Yes @Nisha i got the answer
Good. Try figuring solutions by yourself to the maximum before asking for help. It will help you learn more.
I had to produce the solution so urgently so i asked the help.