我对 ASP.Net 的行为非常奇怪。当我运行以下代码时,抛出异常“具有相同 ID 的多个控件”。添加控件但使用FindControl
.
真正奇怪的是,如果我在调用之前放置一个断点并FindControl
在引发异常的直接窗口中运行调用(到目前为止如此一致),但是当我恢复调试器时,一切正常(!!!)。机器运行完全相同的代码,但它不会再次抛出异常。
关于这个疯狂的事情的最后一件事,今天早些时候,相同的代码在 Page_Load 中,一切正常,但我重新组织了代码并将其移至单独的方法(由 Page_Load 调用)。我越来越有信心这是一个 ASP.Net 错误......
dlAdvanced.DataSource = dsAdvanced;
dlAdvanced.DataBind();
// Load Advanced Values Controls
#region ADV controls
foreach (DataListItem dli in dlAdvanced.Items)
{
DataRow row = dsAdvanced.Tables[0].Rows[dli.ItemIndex];
switch ((string)row["Type"])
{
default:
TextBox tb = new TextBox();
tb.ID = "Input";
dli.FindControl("InputPlace").Controls.Add(tb);
break;
case "System.Int32":
case "System.Decimal":
TextBox tbn = new TextBox();
tbn.ID = "Input";
Image img = new Image();
img.SkinID = "NumberRequired";
img.ApplyStyleSheetSkin(this);
dli.FindControl("InputPlace").Controls.Add(tbn);
dli.FindControl("InputPlace").Controls.Add(img); // Exception happens here
break;
case "System.DateTime":
golf.golfControls.CalendarBox cal = new golf.golfControls.CalendarBox();
cal.ID = "Input";
cal.SkinID = "Calendar";
cal.ApplyStyleSheetSkin(this);
dli.FindControl("InputPlace").Controls.Add(cal);
break;
case "System.Boolean":
RadioButton rb1 = new RadioButton();
rb1.Text = "True";
rb1.ID = "Input";
rb1.GroupName = "grp" + dli.ItemIndex.ToString();
RadioButton rb2 = new RadioButton();
rb2.Text = "False";
rb2.ID = "Input2";
rb2.GroupName = "grp" + dli.ItemIndex.ToString();
dli.FindControl("InputPlace").Controls.Add(rb1);
dli.FindControl("InputPlace").Controls.Add(rb2);
break;
}
}
#endregion
编辑:我只是想到了一些东西并且它起作用了:
DataRow row = dsAdvanced.Tables[0].Rows[dli.ItemIndex];
var inputPlace = dli.FindControl("InputPlace");
switch ((string)row["Type"])
{
default:
TextBox tb = new TextBox();
tb.ID = "Input";
inputPlace.Controls.Add(tb);
break;
case "System.Int32":
case "System.Decimal":
TextBox tbn = new TextBox();
tbn.ID = "Input";
Image img = new Image();
img.SkinID = "NumberRequired";
img.ApplyStyleSheetSkin(this);
inputPlace.Controls.Add(tbn);
inputPlace.Controls.Add(img);
break;
case "System.DateTime":
golf.golfControls.CalendarBox cal = new golf.golfControls.CalendarBox();
cal.ID = "Input";
cal.SkinID = "Calendar";
cal.ApplyStyleSheetSkin(this);
inputPlace.Controls.Add(cal);
break;
case "System.Boolean":
RadioButton rb1 = new RadioButton();
rb1.Text = "True";
rb1.ID = "Input";
rb1.GroupName = "grp" + dli.ItemIndex.ToString();
RadioButton rb2 = new RadioButton();
rb2.Text = "False";
rb2.ID = "Input2";
rb2.GroupName = "grp" + dli.ItemIndex.ToString();
inputPlace.Controls.Add(rb1);
inputPlace.Controls.Add(rb2);
break;
}
所以目前,我的代码工作正常,但这个问题没有解决,所以如果有人知道这个错误,请赐教。