2013-12-09 2 views
2

Недавно я обновил одно из своих старых приложений ASP.NET с .NET 2.0 до .NET 4.5, и это было одно из первых приложений, в которых я попытался использовать управление asp:UpdatePanel. Это приложение для опроса, в котором пользователь может создать опрос, назначить несколько групп вопросов для опроса и несколько типов вопросов для каждой группы вопросов.После того, как после обратной связи, другому элементу управления назначен один и тот же идентификатор - ASP.NET

Когда я использую страницу, где пользователь может редактировать содержимое опроса, который содержит AsyncPostBackTrigger объектов, которые зарегистрированы в LinkButton управления ASP.NET в пользовательских элементах управления типа вопроса, зарегистрированном на странице, я получаю следующее сообщение об ошибке:

Error: Sys.WebForms.PageRequestManagerServerErrorException: An error has occurred because a control with id 'ctl00$PageBody$gvSurveyQuestions$ctl02$ctl03' could not be located or a different control is assigned to the same ID after postback. If the ID is not assigned, explicitly set the ID property of controls that raise postback events to avoid this error.

Пользовательский элемент управления динамически генерируется, на основании которого пользователь выбирает роль группы. В событии OnRowCommand управления DataGrid он определил, какой пользовательский элемент управления отображать на основе выбранного типа вопроса. Вот фрагмент кода:

обследование ASPX страницы:

//grid control to allow user to select the question to edit 
<asp:GridView ID="gvSurveyQuestions" runat="server" AutoGenerateColumns="false" 
    OnRowCommand="gvSurveyQuestions_OnRowCommand" 
    OnRowEditing="gvSurveyQuestions_OnRowEditing" 
    OnRowDeleting="gvSurveyQuestions_OnRowDeleting" 
    CssClass="com_grid" 
    Width="100%" 
    CellPadding="3" 
    CellSpacing="0" 
> 
    <asp:CommandField ButtonType="Link" ShowEditButton="True" ShowDeleteButton="True" 
     ItemStyle-HorizontalAlign="Center" /> 
</asp:GridView> 
<asp:PlaceHolder ID="phEditExcellentPoor" runat="server" Visible="false"> 
    <tr> 
     <td width="100%"> 
      <uc:ExcellentPoor Id="ucEditExcellentPoor" runat="server" EditMode="Edit" /> 
     </td> 
    </tr> 
</asp:PlaceHolder> 

код Позади ASPX страницы:

private readonly string m_CreateUpdateQuestionControlName = "lbCreateUpdateQuestion"; 
private readonly string m_CreateUpdateQuestionText_Edit = "Update Question"; 

protected void Page_Init(object sender, EventArgs e) 
{ 
    //here is the code to set the async postback trigger 
    AsyncPostBackTrigger apExcellentPoorEdit = new AsyncPostBackTrigger(); 
    apExcellentPoorEdit.ControlID = ucEditExcellentPoor.FindControl(this.m_CreateUpdateQuestionControlName).UniqueID; 
    upSurveyQuestions.Triggers.Add(apExcellentPoorEdit); 
} 

код позади пользовательского элемента управления, чтобы установить кнопку ссылки в качестве триггера обратной передачи на обследование ASPX страница:

public event EventHandler lbCreateUpdateQuestionClick; 

protected void lbCreateUpdateQuestion_OnClick(object sender, EventArgs e) 
{ 
    if (this.lbCreateUpdateQuestionClick != null) 
     this.lbCreateUpdateQuestionClick(sender, e); 
} 

Почему я получаю эту ошибку и какие бы хорошие предложения t o посмотреть, где его исправить?

ответ

0

Seems Gridview with multiple CommandField is not working when switched to .Net Framework 4.0. I guess its because of the fact that one cant give an id to command field inside the gridview, so in this case the compiler internally assigns a control id for the first command field and when it encounters the second it assigns the same control id again. So during postback when i try to reload the gridview say when editing a row, it encounters multiple controls with the same id and throws this server error.

I have removed the command fields and instead replaced them with Imagebutton inside TemplateField which has resolved my issue. :)

Предоставлено This post

+0

У меня на моей странице есть два элемента управления asp: GridView, которые содержат столбцы asp: CommandField. Переходим к рефактору 'asp: ButtonField', чтобы проверить, устраняет ли это мою проблему. –

+0

По-прежнему получая ту же ошибку при замене 'asp: CommandField' двумя столбцами' asp: ButtonField' в элементе управления asp: GridView' –

+0

Я смогу решить свою проблему, используя ответ, указанный в этом сообщении: http: // stackoverflow .com/а/18567488/26327 –

0

Я был в состоянии решить мою проблему, заменив asp:CommandField с asp:ButtonField для редактирования и удаления ссылок и переименовании CommandName из Edit в EdT и Удалить в Del

Этот post помог f решить проблему