单击更新按钮时,C#update语句不会更新

时间:2017-12-18 21:51:58

标签: c# sql-server visual-studio

我正在创建c#项目到目前为止插入和删除按钮正在工作,但是当我点击更新按钮时,它提供的数据尚未更新,我无法看到我的代码有什么问题请帮助

public bool Update(Classre c)
{
    bool isSuccess = false;
    SqlConnection conn = new SqlConnection(myconnstring);

    try
    {
        string sql = "UPDATE Class SET ClassName=@ClassName,ClassLevel=@ClassLevel WHERE ClassID=@ClassID";
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.AddWithValue("@ClassName", c.ClassName);
        cmd.Parameters.AddWithValue("@ClassLevel", c.ClassLevel);
        conn.Open();
        int rows = cmd.ExecuteNonQuery();

        if (rows > 0)
        {
            isSuccess = true;
        }
        else
        {
            isSuccess = false;
        }
    }
    catch (Exception ex)
    {

    }
    finally
    {
        conn.Close();
    }

    return isSuccess;
}

这是我的更新按钮代码,我在其中调用包含更新代码的类

private void button3_Click(object sender, EventArgs e)
{
    c.ClassID = int.Parse(textBox1.Text); 
    c.ClassName = textBox2.Text;
    c.ClassLevel = comboBox1.Text;

    bool success = c.Update(c);
    if (success == true)
    {
       // label4.Text = "Data Has been updated";
        MessageBox.Show("Data Has been updated");
        DataTable dt = c.Select();
        dataGridView1.DataSource = dt;

    }
    else
    {
        //label4.Text = "Data Has not been updated";
        MessageBox.Show("Data Has not been updated");

    }
}

1 个答案:

答案 0 :(得分:1)

我更喜欢使用存储过程而不是通过sql,但你可以大大简化这一点。如上所述,你的try / catch比没有一个更差,因为它压制了错误。

public bool Update(Classre c)
{
    USING(SqlConnection conn = new SqlConnection(myconnstring))
    {
        string sql = "UPDATE Class SET ClassName = @ClassName, ClassLevel = @ClassLevel WHERE ClassID = @ClassID";

        USING(SqlCommand cmd = new SqlCommand(sql, conn))
        {
            cmd.Parameters.Add("@ClassName", SqlDbType.VarChar, 4000).Value = c.ClassName;
            cmd.Parameters.Add("@ClassLevel", SqlDbType.Int).Value = c.ClassLevel;
            cmd.Parameters.Add("@ClassID", SqlDbType.Int).Value = c.ClassID;
            conn.Open();
            int rows = cmd.ExecuteNonQuery();
            return rows > 0;
        }
    }
}