根据复选框更新某些框

时间:2015-03-09 15:37:51

标签: c# asp.net

我的页面上有一个复选框,可以在检查时启用我的一半输入(主要是文本框),我需要在C#中执行的操作是编写将更新前半部分行的代码,无论是什么,如果选中该复选框,则添加其他。我有下面尝试的代码,但我怎样才能有效地完成这项任务呢?

protected void Button1_Click(object sender, EventArgs e)
    {
        string updateSQL;
        updateSQL = "UPDATE Projects SET ";
        updateSQL += "ProjectDescription=@ProjectDescription, ";
        updateSQL += "DateAssigned=@StartDate, DueDate=@DueDate, SystemNumber=@SystemNumber ";
        updateSQL += "WHERE ProjectName=@ProjectName";

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectsAndTasksTestConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand(updateSQL, con);

        if (CheckBox_ProjectResults.Checked == false)
        {
            cmd.Parameters.AddWithValue("@ProjectName", DDL1.SelectedItem.Text);
            cmd.Parameters.AddWithValue("@ProjectDescription", UpdatetxtProjectDesc.Text);
            cmd.Parameters.AddWithValue("@StartDate", UpdatetxtStartDate.Text);
            cmd.Parameters.AddWithValue("@DueDate", UpdatetxtEndDate.Text);
            cmd.Parameters.AddWithValue("@SystemNumber", DropDownList2.SelectedItem.Text);



        }
            if (CheckBox_ProjectResults.Checked == true)
            {
                string updateSQL;
                updateSQL = "DateCompleted=@DateCompleted,TrackerNumber=@TrackerNumber, DocumentName=@DocumentName";


                cmd.Parameters.AddWithValue("@DateCompleted", TxtActualEnd.Text);
                cmd.Parameters.AddWithValue("@DocumentName", attachmentFileUpload.FileName);
                cmd.Parameters.AddWithValue("@TrackerNumber", UpdatetxtTrackerNumber.Text);
                cmd.Parameters.AddWithValue("@ProjectName", DDL1.SelectedItem.Text);
                cmd.Parameters.AddWithValue("@ProjectDescription", UpdatetxtProjectDesc.Text);
                cmd.Parameters.AddWithValue("@StartDate", UpdatetxtStartDate.Text);
                cmd.Parameters.AddWithValue("@DueDate", UpdatetxtEndDate.Text);
                cmd.Parameters.AddWithValue("@SystemNumber", DropDownList2.SelectedItem.Text);
            }


            int updated = 0;
            try
            {
                con.Open();
                updated = cmd.ExecuteNonQuery();
                lblResults.Text = updated.ToString() + " record updated.";
            }
            catch (Exception err)
            {
                lblResults.Text = "Error updating. ";
                lblResults.Text += err.Message;
            }
            finally
            {
                con.Close();
            }
    }

更新2

protected void Button1_Click(object sender, EventArgs e)
        {    
            if (CheckBox_ProjectResults.Checked == false)
            {
string updateSQL;
            updateSQL = "UPDATE Projects SET ";
            updateSQL += "ProjectDescription=@ProjectDescription, ";
            updateSQL += "DateAssigned=@StartDate, DueDate=@DueDate, SystemNumber=@SystemNumber ";
            updateSQL += "WHERE ProjectName=@ProjectName";

            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectsAndTasksTestConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand(updateSQL, con);

                cmd.Parameters.AddWithValue("@ProjectName", DDL1.SelectedItem.Text);
                cmd.Parameters.AddWithValue("@ProjectDescription", UpdatetxtProjectDesc.Text);
                cmd.Parameters.AddWithValue("@StartDate", UpdatetxtStartDate.Text);
                cmd.Parameters.AddWithValue("@DueDate", UpdatetxtEndDate.Text);
                cmd.Parameters.AddWithValue("@SystemNumber", DropDownList2.SelectedItem.Text);

try, catch, finally....
            }
                if (CheckBox_ProjectResults.Checked == true)
                {


                   string updateSQL;
            updateSQL = "UPDATE Projects SET ";
            updateSQL += "ProjectDescription=@ProjectDescription, ";
            updateSQL += "DateAssigned=@StartDate, DueDate=@DueDate, SystemNumber=@SystemNumber ";
            updateSQL += "WHERE ProjectName=@ProjectName";

            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectsAndTasksTestConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand(updateSQL, con);


                    cmd.Parameters.AddWithValue("@DateCompleted", TxtActualEnd.Text);
                    cmd.Parameters.AddWithValue("@DocumentName", attachmentFileUpload.FileName);
                    cmd.Parameters.AddWithValue("@TrackerNumber", UpdatetxtTrackerNumber.Text);
                    cmd.Parameters.AddWithValue("@ProjectName", DDL1.SelectedItem.Text);
                    cmd.Parameters.AddWithValue("@ProjectDescription", UpdatetxtProjectDesc.Text);
                    cmd.Parameters.AddWithValue("@StartDate", UpdatetxtStartDate.Text);
                    cmd.Parameters.AddWithValue("@DueDate", UpdatetxtEndDate.Text);
                    cmd.Parameters.AddWithValue("@SystemNumber", DropDownList2.SelectedItem.Text);

try, catch, finally....
                }

1 个答案:

答案 0 :(得分:0)

如果由于格式不佳而创建,则忽略了嵌套:

if (CheckBox_ProjectResults.Checked == false)
{
// code removed
if (CheckBox_ProjectResults.Checked == true)
{
 // code removed
}
}

如果您正确缩进代码,您很容易发现自己的问题:

if (CheckBox_ProjectResults.Checked == false)
{
    // code removed
    if (CheckBox_ProjectResults.Checked == true)
    {
       // code removed
    }
}

您所看到的另一个问题是字符串是不可变的,这意味着它们在分配后不会改变值。
通话结束后:

 SqlCommand cmd = new SqlCommand(updateSQL, con);

此时cmd字符串设置为updateSQL。如果你排了几行

updateSQL += "...awesome sql string... ";

该更改不会更改cmd内的sql字符串,更不用说它会变成神奇有效的sql。

让我们看看我们可以做些什么来解决这个问题。我选择了一个实现,我保持sql的构建和附加的参数。我使用StringBuilder并希望很好地处理连接,因此我将连接和命令包装在using语句中。

// dispose connection
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectsAndTasksTestConnectionString"].ConnectionString))
{
    using(var cmd = new SqlCommand())
    {
        // when we += multiple string we better use a StringBuilder
        StringBuilder updateSQL = new StringBuilder();
        // create our update statement 
        updateSQL.Append("UPDATE Projects SET "); // there is as space on purpose!
        // Checked is already a boolean so not much need
        // to check if this is true it either is or it isn't
        if (CheckBox_ProjectResults.Checked)
        {
            updateSQL.Append("DateCompleted=@DateCompleted,");
            cmd.Parameters.AddWithValue("@DateCompleted", TxtActualEnd.Text);

            updateSQL.Append("TrackerNumber=@TrackerNumber,");
            cmd.Parameters.AddWithValue("@TrackerNumber", UpdatetxtTrackerNumber.Text);

            updateSQL.Append("DocumentName=@DocumentName,");
            cmd.Parameters.AddWithValue("@DocumentName", attachmentFileUpload.FileName);

        else 
        {
            updateSQL.Append("DateAssigned=@StartDate,");
            cmd.Parameters.AddWithValue("@StartDate", UpdatetxtStartDate.Text);

            updateSQL.Append("DueDate=@DueDate,")
            cmd.Parameters.AddWithValue("@DueDate", UpdatetxtEndDate.Text);

            updateSQL.Append("SystemNumber=@SystemNumber,");
            cmd.Parameters.AddWithValue("@SystemNumber", DropDownList2.SelectedItem.Text);
        }
        // this is always there so make it our last one
        updateSQL.Append("ProjectDescription=@ProjectDescription "); // notice no comma but a space!
        cmd.Parameters.AddWithValue("@ProjectDescription", UpdatetxtProjectDesc.Text);

        // no matter what Projectname is always there because it is the where!
        cmd.Parameters.AddWithValue("@ProjectName", DDL1.SelectedItem.Text);
        updateSQL.Append("WHERE ProjectName=@ProjectName");

        cmd.Connection = con;
        // call ToString on the String builder
        cmd.CommandText = updateSQL.ToString();
        int  updated = 0;
        try
        {
            con.Open();
            updated = cmd.ExecuteNonQuery();
            lblResults.Text = String.Format("{0} record(s) updated.", updated);
        }
        catch (SqlException sqlExc)
        {
            lblResults.Text = String.Format("Error updating. {0} - {1} - {2}"
                               , sqlExc.Message
                               , sqlExc.Number
                               , sqlExc.LineNumber);
        }
    }
}