1

嗨,有人可以帮帮我吗?我的目标是允许用户删除数据库中称为“消息”的多行。

通过选中复选框,用户将能够在按下按钮后删除多行。

但是,当我使用下面的代码时,什么都没有发生。有人可以帮我看看我的代码是否有问题吗?谢谢 =)

源代码

<%@ Page Title="" Language="C#" MasterPageFile="~/MainMasterPage.master" AutoEventWireup="true" CodeFile="Messages.aspx.cs" Inherits="Messages" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<SCRIPT runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
    String userLog = Session["loginuser"].ToString();
    if (!IsPostBack)
    {
        LoadData();


    }
}
public void LoadData()
{
String userLog = Session["loginuser"].ToString();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Messages WHERE receiver = '" + userLog + "'",
    "server=19-20\\sqlexpress;database=mpsip;Integrated Security=SSPI");
DataTable table = new DataTable();
adapter.Fill(table);
Repeater1.DataSource = table;
Repeater1.DataBind();

PagedDataSource pds = new PagedDataSource();
pds.DataSource = table.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 10;

int currentPage;

if (Request.QueryString["page"] != null)
{
    currentPage = Int32.Parse(Request.QueryString["page"]);
}
else
{
    currentPage = 1;
}

pds.CurrentPageIndex = currentPage - 1;
Label1.Text = "Page " + currentPage + " of " + pds.PageCount;

if (!pds.IsFirstPage)
{
    linkPrev.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (currentPage - 1);
}

if (!pds.IsLastPage)
{
    linkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (currentPage + 1);
}

Repeater1.DataSource = pds;
Repeater1.DataBind(); 

}

    &nbsp;<asp:Repeater ID="Repeater1" runat="server">

            <itemtemplate>
                <asp:CheckBox ID="CheckBox1" runat="server" />
          <b><%# DataBinder.Eval(Container.DataItem, "title") %></b>

          <br>From UserID: <%# DataBinder.Eval(Container.DataItem, 
                  "mlogin", "{0:d}") %>
              <br />
              Date: <%# DataBinder.Eval(Container.DataItem, 
                  "dateandtime", "{0:d}") %>
              <br />
              MessageID: <%# DataBinder.Eval(Container.DataItem, 
                  "messageID", "{0:d}") %>
                  <br />


       </itemtemplate>
       <separatortemplate>
          <hr>
       </separatortemplate>
        </asp:Repeater>




        <br />
        <asp:HyperLink ID="linkPrev" runat="server">Previous Page</asp:HyperLink>&nbsp;
        <asp:HyperLink ID="linkNext" runat="server">Next Page</asp:HyperLink>

    <br />
    <asp:Button ID="Button7" runat="server" onclick="Button7_Click" 
    Text="Button" />
    <br />
    <br />
    <br />

    <asp:Label ID="Label1" runat="server"></asp:Label>
    <br />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
        Text="Compose Message" />
    <asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
        Text="Sent Messages" />

</div>

   protected void Button7_Click(object sender, EventArgs e)
{

    using (SqlConnection conn = new SqlConnection("Data Source=19-20\\sqlexpress;" + "Initial Catalog = mpsip; Integrated Security = SSPI"))
    {
        conn.Open();
        SqlCommand cmdDel = conn.CreateCommand();
        SqlTransaction transaction = conn.BeginTransaction("MyTransaction");
        cmdDel.Connection = conn;
        cmdDel.Transaction = transaction;
        try
        {
            for (int i = 0; i < Repeater1.Items.Count; i++)
            {
                //This assumes data type of messageID is integer, change (int) to the right type
                cmdDel.CommandText = "delete from messages where messageID = '" + ((String)((DataRow)Repeater1.Items[i].DataItem)["messageID"]) + "'";
                cmdDel.ExecuteNonQuery();

                // Continue your code here

            }
            transaction.Commit();
        }
        catch (Exception ex)
        {
            try
            {
                transaction.Rollback();
            }
            catch (Exception ex1)
            {
                //TODO: write log
            }
        }
    }


}

}

4

2 回答 2

1

您的代码有问题,在这一行:

mysql = "delete from messages where messageID = '" + CheckBox1.Checked + "'";

它应该是:

mysql = "delete from messages where messageID = '" + ((YourClass)Repeater1.Items[i].DataItem).messageID + "'";

你应该使用SqlParameter而不是连接字符串。

此外,SqlCommand 没有被执行,你应该添加这一行:

cmdDel.ExecuteNonQuery();

并且您必须在删除消息后重新加载数据。

此外,您应该在for循环之外初始化SqlConnection对象,并使用SqlTransaction来管理事务。

 using (SqlConnection conn = new SqlConnection("Data Source=19-20\\sqlexpress;" + "Initial Catalog = mpsip; Integrated Security = SSPI"))
 {     
    conn.Open();
    SqlCommand cmdDel = conn.CreateCommand();
    SqlTransaction transaction = conn.BeginTransaction("MyTransaction");
    cmdDel.Connection = conn;
    cmdDel.Transaction = transaction;
    try {
        for (int i = 0; i < Repeater1.Items.Count; i++)
        { 
         //This assumes data type of messageID is integer, change (int) to the right type
         cmdDel.CommandText = "delete from messages where messageID = '" + ((int)((DataRow)Repeater1.Items[i].DataItem)["messageID"]) + "'";
         cmdDel.ExecuteNonQuery();

         // Continue your code here

         }
         transaction.Commit();
         //TODO: reload data here and binding to Repeater
    }
    catch(Exception ex) {
        try {
            transaction.Rollback();
        }
        catch(Exception ex1) {
            //TODO: write log
        }
    }
}
于 2012-07-25T03:53:06.353 回答
0
protected void Button7_Click(object sender, EventArgs e)
{
    bool BindNeeded = false;

    SqlConnection connDelete = new SqlConnection("Data Source=19-20\\sqlexpress;" + "Initial Catalog = mpsip; Integrated Security = SSPI");
    connDelete.Open();
    String mySQL;


    try
    {

        for (int i = 0; i < Repeater1.Items.Count; i++)
        {
            CheckBox CheckBox1 = (CheckBox)
            Repeater1.Items[i].FindControl("CheckBox1");
            if (((CheckBox)Repeater1.Items[i].FindControl("CheckBox1")).Checked)
            {

                //This assumes data type of messageID is integer, change (int) to the right type
                CheckBox CheckBox = (CheckBox)Repeater1.Items[i].FindControl("CheckBox1");
                Literal litMessageId = (Literal)Repeater1.Items[i].FindControl("litMessageId");

                string messageId = litMessageId.Text;
                mySQL = string.Format("delete from messages where messageID = '{0}'", messageId);

                SqlCommand cmdDelete = new SqlCommand(mySQL, connDelete);
                cmdDelete.ExecuteNonQuery();




                // Continue your code here
            }
            else
            {

            }
        }
            if (BindNeeded)
            {
                Repeater1.DataBind();
            }
            else
            {
                Response.Redirect("Messages.aspx");
            }

    }
        catch
    {
        Response.Redirect("Messages.aspx");
    }

}
于 2012-07-31T07:02:17.937 回答