从下拉列表中选择值并单击按钮时如何从数据库中删除

从下拉列表中选择值并单击按钮时如何从数据库中删除

<asp:DropDownList ID="DropDownList3" runat="server"
         DataTextField="number" DataValueField="number"
         AutoPostBack="True"
         DataSourceID="SqlDataSource1">
    </asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="delete" OnClick="Button1_Click" />

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Bank databaseConnectionString %>" SelectCommand="SELECT [number] FROM [Account]"></asp:SqlDataSource>


C#

protected void Button1_Click(object sender, EventArgs e)
{

    if (!Page.IsPostBack)
    {
    SqlConnection conn = new SqlConnection("Data Source=FATIMAH;Initial Catalog=Bank database;Integrated Security=True");
    String sql;
    sql = "delete FROM Account where number ='" + DropDownList3.SelectedValue +"'";
    SqlCommand comm = new SqlCommand(sql, conn);
     conn.Close();
    }

}


最佳答案

正如史蒂夫所说,您需要使用comm.ExecuteNonQuery()并需要打开连接

using (var conn = new SqlConnection("Data Source=FATIMAH;Initial Catalog=Bank database;Integrated Security=True"))
            {
                conn.Open();
                var sql = "delete FROM Account where number ='" + DropDownList3.SelectedValue + "'";
                using (var comm = new SqlCommand(sql, conn))
                {
                    comm.ExecuteNonQuery();
                }
                conn.Close();
            }

关于c# - 从下拉列表中选择值并单击按钮时如何从数据库中删除,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40992119/

10-12 18:39