当我单击按钮并将控件添加到 UpdatePanel 内的占位符时,一切都很好,除非我非常快速地单击几次然后收到如下错误消息:
'Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException: Multiple controls with the same ID 'VehicleRegistrationEnhancedTextBox3_Label' were found. FindControl requires that controls have unique IDs.' when calling method: [nsIDOMEventListener::handleEvent]
[Break On This Error]
我在隐藏字段中保存了一个整数,以创建唯一的 Id,当我点击非常快时,该方法执行了几次,但计数值尚未更新。我尝试使用 C# lock 关键字,但什么也没做。
代码如下:
protected void AddVehicleButton_Click(object sender, EventArgs e)
{
lock (this)
{
int count = Convert.ToInt32(VehicleRegistrationCountHiddenField.Value);
var TBId = "VehicleRegistrationEnhancedTextBox" + count;
IList<Panel> oldPanels = (IList<Panel>)Session["VehiclePanels"] ?? new List<Panel>();
//Seperator
Literal hr = new Literal { Text = "<hr/>" };
//RemoveSpan
Literal span = new Literal() { Text = "<span class=\"RemoveVehicleRegistration\">X</span>" };
//Crop
Control uc = LoadControl("~/Controls/ImageUploadAndCrop/ImageUploadAndCrop.ascx");
uc.ID = "VehicleRegistrationImageUploadAndCrop" + count;
//Vehicle Registration
Label vehicleRegistration = new Label
{
ID = TBId + "_Label",
AssociatedControlID = TBId,
Text = "Vehicle Registration:"
};
EnhancedTextBox vehicleTypeTextBox = new EnhancedTextBox
{
ID = TBId,
Required = true,
RequiredErrorText = "Vehicle Registration is a required field."
};
//Add new controls to the form
Panel newPanel = new Panel();
newPanel.Controls.Add(hr);
newPanel.Controls.Add(span);
newPanel.Controls.Add(vehicleRegistration);
newPanel.Controls.Add(uc);
newPanel.Controls.Add(vehicleTypeTextBox);
AddVehiclePlaceholder.Controls.Add(newPanel);
//Increment the ID count
count++;
VehicleRegistrationCountHiddenField.Value = count.ToString();
//Save the panel to the Session.
oldPanels.Add(newPanel);
Session["VehiclePanels"] = oldPanels;
//Go back to the same wizard step.
ShowStep2HiddenField.Value = "true";
ShowStep3HiddenField.Value = "false";
}
}