我在一个按钮的点击事件中为占位符添加了一组控件。我可以添加一次控件,但第二次我收到此消息。我正在使用Ajax Toolkit来制作一些自定义控件。
发生了System.InvalidOperationException 消息=在PreRender之后可能无法注册Extender控件。 来源= System.Web.Extensions程序 堆栈跟踪: 在System.Web.UI.ScriptControlManager.RegisterExtenderControl [TExtenderControl](TExtenderControl extenderControl,Control targetControl)。
代码如下:
/// <summary>
/// Handles the Click event of the AddWitnessButton control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks></remarks>
protected void AddWitnessButton_Click(object sender, EventArgs e)
{
int count = Convert.ToInt32(WitnessCountHiddenField.Value);
var fullNameTextBoxId = "FullNameEnhancedTextBox" + count;
var mobileFilteredTextBoxId = "MobileFilteredTextBox" + count;
IList<Panel> oldPanels = (IList<Panel>)Session["WitnessPanels"] ?? new List<Panel>();
//Container
Panel panel = new Panel();
//Seperator
Literal hr = new Literal { Text = "<HR/>" };
//Full Name
Label fullNameLabel = new Label
{
ID = fullNameTextBoxId + "_Label",
AssociatedControlID = fullNameTextBoxId,
Text = "Full Name:"
};
EnhancedTextBox fullNameEnhancedTextBox = new EnhancedTextBox
{
ID = fullNameTextBoxId,
Required = true,
RequiredErrorText = "Full Name is a required field."
};
//Mobile
Label mobileLabel = new Label
{
ID = mobileFilteredTextBoxId + "_Label",
AssociatedControlID = mobileFilteredTextBoxId,
Text = "Mobile:"
};
FilteredTextBox mobileFilteredTextBox = new FilteredTextBox
{
ID = mobileFilteredTextBoxId,
FilterMode = FilterModes.ValidChars,
ValidChars = "0123456789+()",
Required = true,
RequiredErrorText = "Mobile is a required field."
};
//Readd previously added panels
foreach (var addedPanel in oldPanels)
{
AddWitnessPlaceHolder.Controls.Add(addedPanel);
}
//Add new controls to the form
Panel newPanel = new Panel();
newPanel.Controls.Add(hr);
newPanel.Controls.Add(fullNameLabel);
newPanel.Controls.Add(fullNameEnhancedTextBox);
newPanel.Controls.Add(mobileLabel);
newPanel.Controls.Add(mobileFilteredTextBox);
AddWitnessPlaceHolder.Controls.Add(newPanel);
//Increment the ID count
count++;
WitnessCountHiddenField.Value = count.ToString();
//Save the panel to the Session.
oldPanels.Add(newPanel);
Session["WitnessPanels"] = oldPanels;
//Go back to the same wizard step.
ShowStep2HiddenField.Value = "false";
ShowStep3HiddenField.Value = "true";
}
protected void Page_PreRender(object sender, EventArgs e)
{
if(IsPostBack)
{
//Readd previously added panels
var vehicleControls = (IList<Panel>)Session["VehiclePanels"] ?? new List<Panel>();
if (vehicleControls.Any())
{
foreach (var addedPanel in vehicleControls)
{
AddVehiclePlaceholder.Controls.Add(addedPanel);
}
}
var witnessControls = (IList<Panel>)Session["WitnessPanels"] ?? new List<Panel>();
if (witnessControls.Any())
{
foreach (var addedPanel in witnessControls)
{
AddWitnessPlaceHolder.Controls.Add(addedPanel);
}
}
}
}