asp.net 按钮保存或更新SQL数据库

wkyowqbh  于 2023-06-25  发布在  .NET
关注(0)|答案(1)|浏览(126)

我有一个按钮,如果Dropdownlist5中没有值,我希望它将数据保存到SQL数据库,但如果Dropdownlist5中有值,我希望该按钮更新SQL中的现有数据。问题是当Dropdownlist5选择了一个值时,它只是在sql数据库中创建一个新条目,而不更新sql中的现有条目。

protected void Button1_Click(object sender, EventArgs e)
    {
        if (DropDownList1.SelectedValue == "" ||  DropDownList2.SelectedValue == "" || TextBox1.Text == "")
        {
            Label1.Text = "Fill In All Fields";
        }
        if (DropDownList5.SelectedValue !=null)
        {
            SqlConnection con = new SqlConnection("Data Source=ucpdapps2;Initial Catalog=OnCallWeb;Integrated Security=True");
            con.Open();
            SqlCommand comm = new SqlCommand("Update Dispatcher_Roles set Name = '" + DropDownList1.SelectedValue + "',Position = '" + DropDownList2.SelectedValue + "',Roles = '" + TextBox1.Text + "',Status = '" + DropDownList3.SelectedValue + "',DispatcherCovering = '" + DropDownList4.SelectedValue + "' where Name='" + DropDownList1.SelectedValue + "'", con);
            comm.ExecuteNonQuery();
            con.Close();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Successfully Updated');", true);
            ClearAllData();
        }

        else
        {
            SqlConnection con = new SqlConnection("Data Source=ucpdapps2;Initial Catalog=OnCallWeb;Integrated Security=True");
            con.Open();
            SqlCommand comm = new SqlCommand("Insert into Dispatcher_Roles values ('" + DropDownList1.SelectedValue + "','" + DropDownList2.SelectedValue + "','" + TextBox1.Text + "','" + DropDownList3.SelectedValue + "','" + DropDownList4.SelectedValue + "')", con);
            comm.ExecuteNonQuery();
            con.Close();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Successfully Added');", true);
            ClearAllData();
            Label1.Text = "";
        }
    }

相关问题