Asp.Net中的嵌套中继器,适合初学者

时间:2015-04-17 17:34:41

标签: c# asp.net

我在asp.net中使用repeater来显示网页中的数据,现在我想在树中显示数据,例如"主要类别 - >子类别"等...

我有两个表评论和重播评论。我能够成功地显示评论,但无法显示对这些评论的回复。

Asp.Net代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Detail.aspx.cs" Inherits="Detail" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style>
        body
        {
           padding:0;
           margin:0;
            background-color:whitesmoke;
        }
        .main
        {
            border:1px solid black;
            background-color:silver;
            width:40%;
            height:auto;
            background-repeat:repeat-y;
            padding:0;
            margin:0;

        }
        .question
        {


            text-align:left;
        }
        .question .ques
        {
            padding-left:20px;

        }
        .question .ans{
            padding-left:20px;

        }
        .comment{

        }
        panel
        {
            margin-bottom:20px;
        }
        table
        {

            width:50%;

        }
        td
        {
            border-bottom:1px solid white;
            margin-bottom:10px;
        }
        .rep
        {
            top:-20px;
        }

    </style>
</head>
<body>
    <form id="form1" runat="server" style="position:relative; text-align:center;">
        <div class="main">
        <div class="question">
        <asp:Label ID="Question" ForeColor="Red" runat="server" Text="Question"></asp:Label>&nbsp;<asp:Label CssClass="ques" ID="Ques" runat="server" Height="20px" Width="400px"></asp:Label><br />
        <asp:Label ID="Answer" ForeColor="Green" runat="server" Text="Answer"></asp:Label>&nbsp; <asp:Label ID="Ans" CssClass="ans" runat="server" Text="" Height="60px" Width="400px"></asp:Label>
        </div>
        <div class="comment">

            <table>


         <asp:Panel ID="Panel1" runat="server" Height="140px" Width="378px">
            <asp:Repeater ID="repUserComments" runat="server" OnItemCommand="repUserComments_ItemCommand" OnItemDataBound="repUserComments_ItemDataBound">
                <ItemTemplate>
                   <tr>
                       <td>
                     <p>
                        <%#Eval("Username") %>
                        Commented on
                        <%#Eval("Date_Created") %>
                    </p>

                    <div><%#Eval("Comment") %></div>  


        <p>
            <asp:Button ID="replay" runat="server" CssClass="rep" OnClick="replay_Click" Text="Replay"/>

        </p>

 </td>

                       </tr>

                    <tr>
                         <td>
                        <asp:Label ID="repuser" Visible="false" runat="server">Username</asp:Label>&nbsp; <br />
                             <asp:TextBox ID="uname" runat="server" Visible="false"></asp:TextBox><br />
                        <asp:Label ID="repcoment" Visible="false" runat="server">Replay</asp:Label>&nbsp; <br />
                             <asp:TextBox ID="comreplay" runat="server" Visible="false"></asp:TextBox><br />
                        <asp:Button ID="savereplay" runat="server" Text="Replay Post" Visible="false" OnClick="savereplay_Click"/>
                    </td>
                    </tr>
                   <asp:Repeater ID="replay_comments" runat="server" OnItemDataBound="replay_comments_ItemDataBound">
                       <ItemTemplate>
                       <p>
                        <%#Eval("username") %>
                        Commented on
                        <%#Eval("date") %>
                    </p>

                    <div><%#Eval("replay") %></div>  
                           </ItemTemplate>  
                   </asp:Repeater>

                </ItemTemplate>
            </asp:Repeater>
        </asp:Panel>
                </table>
            </div>


        <div style="text-align:left; margin-left:40px;">
        <asp:Label ID="User" runat="server" Text="User"></asp:Label>&nbsp;<br />
        <asp:TextBox ID="username" runat="server" style="margin-bottom: 14px"></asp:TextBox>
        <p>
            <asp:Label ID="coment" runat="server" Text="Comment"></asp:Label>&nbsp;<br />
        <asp:TextBox ID="Comment" runat="server" Height="85px" Width="147px" MaxLength="500" Rows="10"></asp:TextBox>
        </p>
        <p>
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Post Comment" />
        </p>
       </div>

            </div>
    </form>

</body>
</html>

代码背后

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;


public partial class Detail : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("data source=MSZ900; integrated security=true; initial catalog=Test");

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) //----- Make sure you always bind your databound controls after this.
        {
            con.Open();
            string st = Request.QueryString["id"];
            SqlCommand cmd = new SqlCommand("select * from faq where ID='" + st + "'", con);
            SqlCommand cmdd = new SqlCommand("select * from comment where Qid='" + st + "'", con);

            cmdd.ExecuteNonQuery();
            cmd.ExecuteNonQuery();

            SqlDataReader drr;
            SqlDataReader dr;


            dr = cmd.ExecuteReader();
            if (dr.Read())
            {


                Ques.Text = dr["Question"].ToString();
                Ans.Text = dr["Answer"].ToString();
            }
            dr.Close();
            drr = cmdd.ExecuteReader();
            //---- bind comments
            if (drr.HasRows)
            {

                repUserComments.DataSource=drr;

                repUserComments.DataBind();


            }
            drr.Close();
            con.Close();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        con.Open();
        string st = Request.QueryString["id"];
        DateTime dt = DateTime.Now;
        string qry = "insert into comment(ID,Username,Comment,Date_Created,Qid)values('" + st + "','" + username.Text + "','" + Comment.Text + "','" + dt + "','" + st + "')";
        SqlCommand cmd = new SqlCommand(qry, con);
        cmd.ExecuteNonQuery();
        username.Text = string.Empty;
        Comment.Text = string.Empty;
        Response.Redirect("detail.aspx?id=" + st);

        con.Close();
    }
    protected void repUserComments_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if(e.CommandName=="preplay")
        {
            if (e.Item.ItemType == ListItemType.Item)
            {
                con.Open();

               TextBox username = (TextBox)e.Item.FindControl("cusername");
                TextBox replay = (TextBox)e.Item.FindControl("commentreplay");
                string st = Request.QueryString["id"];
                DateTime dt = DateTime.Now;
                string qry = "insert into comment_replay(username,replay,date)values('" + username.Text + "','" + replay.Text + "','" + dt + "')";
                SqlCommand cmd = new SqlCommand(qry, con);
                cmd.ExecuteNonQuery();


                username.Text = string.Empty;
                replay.Text = string.Empty;

                con.Close();

            }
        }



    }
    protected void replay_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        RepeaterItem rpt = (RepeaterItem)btn.NamingContainer;
        Label repu = (Label)rpt.FindControl("repuser");
        TextBox user =(TextBox)rpt.FindControl("uname");
        Label repcomment = (Label)rpt.FindControl("repcoment");
        TextBox cmnt = (TextBox)rpt.FindControl("comreplay");
        Button save = (Button)rpt.FindControl("savereplay");
        user.Visible = true;
        cmnt.Visible = true;
        save.Visible = true;
        repu.Visible = true;
        repcomment.Visible = true;

    }
    protected void savereplay_Click(object sender, EventArgs e)
    {
        con.Open();
        string st = Request.QueryString["id"];
        Button sv = (Button)sender;
        RepeaterItem rptt = (RepeaterItem)sv.NamingContainer;
        TextBox user = (TextBox)rptt.FindControl("uname");
        TextBox cmnt = (TextBox)rptt.FindControl("comreplay");
        DateTime dt = DateTime.Now;
        string qry = "insert into comment_replay(username,replay,date,Qid)values('" + user.Text + "','" + cmnt.Text + "','" + dt + "','"+st+"')";
                SqlCommand cmd = new SqlCommand(qry, con);
                cmd.ExecuteNonQuery();
                con.Close();


    }

    protected void replay_comments_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {

    }
    protected void repUserComments_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        string st = Request.QueryString["id"];
        RepeaterItem item = e.Item;
        if ((item.ItemType == ListItemType.Item) ||
            (item.ItemType == ListItemType.AlternatingItem))
        {
          Repeater replay = (Repeater)item.FindControl("replay_comments");

          replay.DataSource = ((DataRowView)item.DataItem).CreateChildView("repUserComments");
            replay.DataBind();
        }
    }
}

更新

我能够使用嵌套转发器,但是知道问题是如果我在评论1上重播,那么重播也会在评论2,评论3等下面显示,但我希望它只会在指定下显示评论(评论1)。

我的更新代码是......

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;


public partial class Detail : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("data source=MSZ900; integrated security=true; initial catalog=Test; MultipleActiveResultSets=true");

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) //----- Make sure you always bind your databound controls after this.
        {
            con.Open();
            string st = Request.QueryString["id"];
            SqlCommand cmd = new SqlCommand("select * from faq where Qid='" + st + "'", con);
            SqlCommand cmdd = new SqlCommand("select * from comment where Qid='" + st + "'", con);

            cmdd.ExecuteNonQuery();
            cmd.ExecuteNonQuery();

            SqlDataReader drr;
            SqlDataReader dr;


            dr = cmd.ExecuteReader();
            if (dr.Read())
            {


                Ques.Text = dr["Question"].ToString();
                Ans.Text = dr["Answer"].ToString();
            }
            dr.Close();
            drr = cmdd.ExecuteReader();
            //---- bind comments
            if (drr.HasRows)
            {

                repUserComments.DataSource=drr;

                repUserComments.DataBind();


            }
            drr.Close();
            con.Close();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        con.Open();
        string st = Request.QueryString["id"];
        DateTime dt = DateTime.Now;
        string qry = "insert into comment(Username,Comment,Date_Created,Qid)values('" + username.Text + "','" + Comment.Text + "','" + dt + "','" + st + "')";
        SqlCommand cmd = new SqlCommand(qry, con);
        cmd.ExecuteNonQuery();
        username.Text = string.Empty;
        Comment.Text = string.Empty;
        Response.Redirect("detail.aspx?id=" + st);

        con.Close();
    }
    protected void repUserComments_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if(e.CommandName=="preplay")
        {
            if (e.Item.ItemType == ListItemType.Item)
            {
                con.Open();

               TextBox username = (TextBox)e.Item.FindControl("cusername");
                TextBox replay = (TextBox)e.Item.FindControl("commentreplay");
                string st = Request.QueryString["id"];
                DateTime dt = DateTime.Now;
                string qry = "insert into comment_replay(username,replay,date)values('" + username.Text + "','" + replay.Text + "','" + dt + "')";
                SqlCommand cmd = new SqlCommand(qry, con);
                cmd.ExecuteNonQuery();


                username.Text = string.Empty;
                replay.Text = string.Empty;

                con.Close();

            }
        }



    }
    protected void replay_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        RepeaterItem rpt = (RepeaterItem)btn.NamingContainer;
        Label repu = (Label)rpt.FindControl("repuser");
        TextBox user =(TextBox)rpt.FindControl("uname");
        Label repcomment = (Label)rpt.FindControl("repcoment");
        TextBox cmnt = (TextBox)rpt.FindControl("comreplay");
        Button save = (Button)rpt.FindControl("savereplay");
        user.Visible = true;
        cmnt.Visible = true;
        save.Visible = true;
        repu.Visible = true;
        repcomment.Visible = true;

    }
    protected void savereplay_Click(object sender, EventArgs e)
    {
        con.Open();
        string st = Request.QueryString["id"];
        Button sv = (Button)sender;
        RepeaterItem rptt = (RepeaterItem)sv.NamingContainer;
        TextBox user = (TextBox)rptt.FindControl("uname");
        TextBox cmnt = (TextBox)rptt.FindControl("comreplay");
        DateTime dt = DateTime.Now;
        string qry = "insert into comment_replay(username,replay,date,Commentid)values('" + user.Text + "','" + cmnt.Text + "','" + dt + "','"+st+"')";
                SqlCommand cmd = new SqlCommand(qry, con);
                cmd.ExecuteNonQuery();
                con.Close();


    }

    protected void replay_comments_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
    }

    protected void repUserComments_ItemDataBound(object sender, RepeaterItemEventArgs e)



    {
      if(e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem)
      {

          Repeater rept = e.Item.FindControl("replay_comments") as Repeater;
          string id = Request.QueryString["id"].ToString();
          //string id = DataBinder.Eval(e.Item.DataItem, "Commentid").ToString();
          SqlCommand cmd = new SqlCommand("select username,date,replay from comment_replay where Commentid='" +id+ "'", con);

          DataTable dt = new DataTable();

          SqlDataAdapter dap = new SqlDataAdapter(cmd);
          dap.Fill(dt);
          rept.DataSource = dt;
          rept.DataBind();
      }



    }
}

1 个答案:

答案 0 :(得分:0)

当您点击&#39;重播&#39;按钮,replay_Click()只是显示隐藏的元素。

当您点击&#39;重播帖子&#39;时,savereplay_Click()会将您的表单提交给自己,并且由于Request.QueryString["id"]是在网址上传递的问题ID,因此您始终保存您的重播错误的身份。

repUserComments_ItemDataBound再次呼叫Request.QUeryString["id"]时,再次将其作为来自网址的问题ID。这就是为什么你的所有评论都有相同的重播。

您需要更好地构建代码并在相应的get / post方法上传递正确的ID,否则您将始终在数据库中保存错误的信息。

修改

如评论中所述,要包含您使用的隐藏字段(不知道您的数据库架构,因此如果需要,请使用Eval来更正字段):

<asp:HiddenField ID="CmntId" runat="server" value='<%#Eval("CommentId") %>' />
<asp:Label ID="repuser" Visible="false" runat="server">Username</asp:Label>&nbsp; <br />
<asp:TextBox ID="uname" runat="server" Visible="false"></asp:TextBox><br />

然后在savereplay_Click()

HiddenField hiddenField = (HiddenField)rptt.FindControl("CmntId");
string st = hiddenField.Value;