C#: Update Query doesn't work!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JFKJr
    New Member
    • Jul 2008
    • 126

    C#: Update Query doesn't work!

    Hello Guys,

    I am trying to update a table using the following C# code, but it is not working.

    Please let me know what I am missing. Thanks.

    Code:
    string topic1 = Topic1TextBox.Text;
    int WeekID = 1;
    
    SqlConnection conn = new SqlConnection();
    DataSet ds = new DataSet();
    conn.ConnectionString = "" //defined my connection string here
    conn.Open();
    
    SqlDataAdapter da = new SqlDataAdapter("Select * From ClassTopics", conn);
    SqlCommand cmd = new SqlCommand("Update ClassTopics Set TopicName=@TopicName Where ClassNumber='1' AND WeekID=@WeekID", conn);
    
    cmd.Parameters.Add(new SqlParameter("@TopicName", System.Data.SqlDbType.NVarChar));
    cmd.Parameters["@TopicName"].SourceColumn="TopicName";
    
    cmd.Parameters.Add(new SqlParameter("@WeekID", System.Data.SqlDbType.Int));
    cmd.Parameters["@WeekID"].SourceColumn="WeekID";
    
    da.UpdateCommand=cmd;
    da.Fill(ds, "ClassTopics");
    ds.Tables["ClassTopics"].Rows[2]["TopicName"]=topic1;
    ds.Tables["ClassTopics"].Rows[3]["WeekID"]=weekID;
    da.Update(ds, "ClassTopics");
    conn.Close();
  • Ramk
    New Member
    • Nov 2008
    • 61

    #2
    Try changing Where ClassNumber=1
    in the command object of
    SqlCommand cmd = new SqlCommand("Upd ate ClassTopics Set TopicName=@Topi cName Where ClassNumber='1' AND WeekID=@WeekID" , conn);

    Comment

    • shweta123
      Recognized Expert Contributor
      • Nov 2006
      • 692

      #3
      Hi,

      The update query may not be working because there are no records for the condition you have specified in the update query. You can debug the same query by running the query into Query Analyzer.

      Comment

      • Ramk
        New Member
        • Nov 2008
        • 61

        #4
        Originally posted by shweta123
        Hi,

        The update query may not be working because there are no records for the condition you have specified in the update query. You can debug the same query by running the query into Query Analyzer.
        Obviously if no records are there in the table with ClassNumber=1, then it will not update at all!!!.
        My intention is to correct the way the questioner used the ClassNumber parameter in the Update query. I guess, it was misinterpreted as a varchar by the thread starter. So, just guided about the mistake(probabl y). If it is of type varchar, then probably, the question may not arise at all!

        Comment

        Working...