由于代码而显示多条记录

时间:2011-03-24 12:36:33

标签: c# asp.net html

您好我显示多条记录,当我按下按钮点击时,它们没有正确降序。

文本被添加到数据库中并显示但是我在页面上显示了两组记录,并且插入的文本被下推到第一个多记录的底部。

如何更正此问题,以便我只在页面上获得一次返回,并将注释(来自db的文本)设置为desc。

代码:

   protected void Page_Load(object sender, EventArgs e)
    {
        string theUserId = Session["UserID"].ToString();
        PopulateWallPosts(theUserId);
    }
    private void PopulateWallPosts(string userId)
    {

        using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=x; Password=x;"))
        {
            cn.Open();
            using (OdbcCommand cmd = new OdbcCommand("SELECT Wallpostings FROM WallPosting WHERE UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
            {
                using (OdbcDataReader reader = cmd.ExecuteReader())
                {



                    while (reader.Read())
                    {
                        System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                        div.Style["float"] = "left";
                        Image img = new Image();
                        img.ImageUrl = "~/userdata/2/uploadedimage/batman-for-facebook.jpg";
                        img.AlternateText = "Test image";
                        div.Controls.Add(img);
                        test1.Controls.Add(div);

                        System.Web.UI.HtmlControls.HtmlGenericControl div1 = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                        div1.InnerText = String.Format("{0}", reader.GetString(0));

                        div1.Style["float"] = "left";
                        test1.Controls.Add(div1);

                        System.Web.UI.HtmlControls.HtmlGenericControl div2 = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                        div2.Style["clear"] = "both";
                        test1.Controls.Add(div2);
                    }
                }
            }
        }
    }








    protected void Button1_Click(object sender, EventArgs e)
    {
        string theUserId = Session["UserID"].ToString();
        using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=x; Password=x;"))
        {
            cn.Open();
            using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings) VALUES (" + theUserId + ", '" + TextBox1.Text + "')", cn))
            {
                cmd.ExecuteNonQuery();
            }
        }
        PopulateWallPosts(theUserId);
    }
}

2 个答案:

答案 0 :(得分:1)

只需在循环前清除占位符控件:

test1.Controls.Clear();
while (reader.Read())
{
   ...
}

答案 1 :(得分:0)

调用PopulateWallPosts(theUserId);在Page_Prerender上而不是在Load和on Click上两次。

PS您的代码易受SQL注入和XSS攻击。不要相信用户的输入:)