我在youtube上关注此代码,但此代码对我不起作用..
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form> </body>
这里的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication4
{
public partial class WebForm1 : System.Web.UI.Page
{
List<string> controlIdList = new List<string>();
int counter = 0;
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
controlIdList = (List<string>)ViewState["contrloIdList"];
foreach (string Id in controlIdList)
{
counter++;
TextBox tb = new TextBox();
tb.ID = Id;
LiteralControl lineBreak = new LiteralControl();
PlaceHolder1.Controls.Add(tb);
PlaceHolder1.Controls.Add(lineBreak);
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
counter++;
TextBox tb = new TextBox();
tb.ID = "textbox" + counter;
tb.Text = "new textbox";
LiteralControl lineBreak = new LiteralControl("<br />");
PlaceHolder1.Controls.Add(tb);
PlaceHolder1.Controls.Add(lineBreak);
controlIdList.Add(tb.ID);
ViewState["controlIdList"] = controlIdList;
}
}}
错误是
描述:执行期间发生了未处理的异常 当前的网络请求。请查看堆栈跟踪了解更多信息 有关错误的信息以及它在代码中的起源。
异常详细信息:System.NullReferenceException:对象引用 没有设置为对象的实例。
第17行:
第18行:controlIdList =(List)ViewState [“contrloIdList”]; 块引用
第19行:foreach(controlIdList中的字符串Id)
第20行:{
第21行:counter ++;