如果用户多次单击按钮,我想多次显示文本。例如,如果我第四次单击按钮,我希望出现四个文本。但是,发生了一个问题,阻止了它多次出现。
如果用户三按按钮,我期望它会像这样显示:
Hello world
Hello world
Hello world
但这向我展示了这一点:
Hello world
有没有人可以帮助我解决这个问题。
这是源代码:
Webform1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="addlabels.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Button ID="add" runat="server" Text="Add more" OnClick="add_click"/>
</div>
</form>
</body>
</html>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Text;
namespace addlabels
{
public partial class WebForm1 : System.Web.UI.Page
{
int pressNumberOfTimes;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void add_click(object sender, EventArgs e)
{
// Add the panel
pressNumberOfTimes++;
Label lbl_homeCarouselAdd = new Label();
// Set the label's Text and ID properties.
lbl_homeCarouselAdd.ID = "lbl_homeCarouselAdd" + pressNumberOfTimes;
StringBuilder strDiv = new StringBuilder();
strDiv.Append(string.Format(@"<p class='style'>Hello world</p>"));
lbl_homeCarouselAdd.Text = strDiv.ToString();
Panel1.Controls.Add(lbl_homeCarouselAdd);
}
}
}
解决方案1:您只是将新标签替换为旧标签,而没有添加到现有标签,这就是即使多次单击按钮也看不到多个标签的原因。
替换为:
lbl_homeCarouselAdd.Text = strDiv.ToString();
具有以下内容:
lbl_homeCarouselAdd.Text += strDiv.ToString();
解决方案2:
您无需每次都创建标签,因此可以将标签声明移到函数外部。
解决方案3:
每次将所有动态创建的控件都删除时,将页面回发到服务器时(在这种情况下,标签将被删除)。因此,您应该将标签数据保留在一些变量中,以备下次使用。在这里,我已经使用StringBuilder保存了旧标签数据。要获得更好的方法,请参见链接动态创建的控件丢失数据
修改后的代码应如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Text;
namespace addlabels
{
public partial class WebForm1 : System.Web.UI.Page
{
int pressNumberOfTimes;
Label lbl_homeCarouselAdd = new Label();
static StringBuilder strDiv = new StringBuilder();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void add_click(object sender, EventArgs e)
{
// Add the panel
pressNumberOfTimes++;
// Set the label's Text and ID properties.
lbl_homeCarouselAdd.ID = "lbl_homeCarouselAdd" + pressNumberOfTimes;
strDiv.Append(string.Format(@"<p class='style'>Hello world</p>"));
lbl_homeCarouselAdd.Text += strDiv.ToString();
Panel1.Controls.Add(lbl_homeCarouselAdd);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句