This is a migrated thread and some comments may be shown as answers.

Drop Downs in Autogenerated Edit Form losing values after second postback

2 Answers 83 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Jeremy
Top achievements
Rank 1
Jeremy asked on 29 Dec 2011, 07:57 PM
Am having truoble with my autogenerated edit form after posting back the if an EntityDataSourceValidationException is thrown.  I am overriding the Entity DataSource Inserting Event and using automatic inserts on the grid. 

The first time the exception is thrown the drop downs in my edit form retain their values and I am able to insert the values after correcting the errors on the form.

However, if I try to insert again without correcting the validation errors, after postback the values in the drop down lists are lost and the edit form is then unusable.

Hoping to hear if this the right way to do this, or if I need to just allow the grid to auto insert withough overriding the Entity Data Source Inserting Event.

I am providing the grid code, entity data source and the code for the inserting event.

<ajci:JMGrid ID="ItemsGrid" runat="server" DataSourceID="edsAssetManager" AutoGenerateColumns="false" Skin="Windows7"
     AllowAutomaticInserts="true" AllowAutomaticDeletes="true" AllowAutomaticUpdates="false" DataKeyNames="id" OnUpdateCommand="GridOnUpdate">
    <ExportSettings IgnorePaging="true" OpenInNewWindow="true" ExportOnlyData="true"
        FileName="AssetList">
        <Excel Format="Html" FileExtension="xls" />
    </ExportSettings>
    <MasterTableView EditMode="PopUp" AllowFilteringByColumn="true" CommandItemDisplay="Top"
        CommandItemSettings-AddNewRecordText="Add Items" DataKeyNames="id" TableLayout="Fixed">
        <EditFormSettings CaptionFormatString="Add/Edit Item" PopUpSettings-Modal="true" EditFormType="AutoGenerated">
    </EditFormSettings>
 
    <CommandItemTemplate>
        <asp:LinkButton runat="server" ID="lnkAdd" Text="Add Item" CssClass="iconAdd" CommandName="InitInsert" ></asp:LinkButton>
        <asp:LinkButton ID="btnManualRefresh" CssClass="iconRefresh" runat="server" Text="Refresh Data" OnCommand="GridRefresh" />
        <asp:LinkButton ID="ExportToExcelButton2" runat="server" OnClick="ExportData" CommandArgument="Excel" Text="Export To Excel" CssClass="buttonExcel" />
    </CommandItemTemplate>
    <Columns>
        <telerik:GridTemplateColumn AllowFiltering="false" ItemStyle-Width="100px" HeaderStyle-Width="100px" ReadOnly="true">
            <ItemTemplate>
                <div>
                    <asp:LinkButton ID="btnEdit" CommandName="Edit" runat="server"  CssClass="iconEdit" Text=" "></asp:LinkButton>
                    <asp:LinkButton ID="lbDeleteRecord" runat="server" CssClass="iconDelete" Text=" " CommandName="Delete" CommandArgument='<%# Eval("id") %>' OnClientClick="javascript:return confirm('Removing this item will also clear its related history.  Continue?')"></asp:LinkButton>
                    <a href="#" onclick="openRadWindow('<%#DataBinder.Eval(Container.DataItem,"id") %>'); return false;">
                        <img src="../Assets/images/icons/icon-magnifying-glass.png" />
                    </a>
                     
                    <asp:Image ID="imgNote" runat="server" ImageUrl="../Assets/images/icons/icon-notes.png" />
                    <telerik:RadToolTip ID="tooltpNotes" runat="server" TargetControlID="imgNote" RelativeTo="Element"
                        Position="BottomCenter" RenderInPageRoot="true" ManualClose="true">
                        <p></p>
                        <div>
                            <asp:Label id="ttpAssetNote" runat="server" Text='<%# Eval("notes")%>'></asp:Label>
                        </div>
                    </telerik:RadToolTip>
 
                    <asp:Image ID="imgComment" runat="server" ImageUrl="../Assets/images/icons/icon-comment.png" />
                    <telerik:RadToolTip ID="tooltpComment" runat="server" TargetControlID="imgComment" RelativeTo="Element"
                        Position="BottomCenter" RenderInPageRoot="true" ManualClose="true">
                        <p></p>
                        <div>
                            <asp:Label id="ttpAssetComment" runat="server" Text='<%# Eval("comment")%>'></asp:Label>
                        </div>
                    </telerik:RadToolTip>
                    <asp:Image ID="imgQRTag" runat="server" CssClass="iconQR" ImageUrl='<%# AssetManager.Helper.QRImage.GetQRIMageURL(Eval("tag.assetTag").ToString()) %>' />
                    <telerik:RadToolTip ID="tltpQRStatus" runat="server" TargetControlID="imgQRTag"
                    RelativeTo="Element" Position="BottomCenter" RenderInPageRoot="true" EnableShadow="true"
                    ManualClose="true">
                        <div >
                            <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# AssetManager.Helper.QRImage.GetQRIMageURL(Eval("tag.assetTag").ToString()) %>' Target="_blank" Text="Asset QR Code"/>
                        </div>
                        <div id="RenderedQR">
                            <asp:Image ID="qrImage" runat="server" ImageUrl='<%# AssetManager.Helper.QRImage.GetQRIMageURL(Eval("tag.assetTag").ToString()) %>'
                                Title='<%# Eval("tag.assetTag") + ".png" %>' ClientIDMode="Static"/>
                        </div>
                        <div>
                            <asp:Label ID="lblQRAssetID" runat="server" Text='<%# Eval("tag.assetTag") %>'></asp:Label>
                        </div>
                    </telerik:RadToolTip>                    </div>
            </ItemTemplate>
        </telerik:GridTemplateColumn>
        <telerik:GridDropDownColumn  UniqueName="DDLassetTag" DataSourceID="edsAssetTag" SortExpression="assetTag" ListTextField="assetTag" ListValueField="id" HeaderText="AssetTag" DataField="tagID" EmptyListItemText="Choose an Asset Tag" EmptyListItemValue="" EnableEmptyListItem="true" HeaderStyle-HorizontalAlign="Center" FilterControlWidth="95px" HeaderStyle-Width="135px" ItemStyle-Width="100px"/>
       <telerik:GridBoundColumn DataField="itemName" AllowFiltering="true" AllowSorting="true" HeaderText="Item Name" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Center" FilterControlWidth="120px" HeaderStyle-Width="160px"></telerik:GridBoundColumn>
        <telerik:GridDropDownColumn UniqueName="DDLManufacturer" DataSourceID="edsManufacturer" SortExpression="mfgName" ListTextField="mfgName" ListValueField="id" HeaderText="Manufacturer" DataField="mfgID" EmptyListItemText="Choose a Manufacturer" EmptyListItemValue="" EnableEmptyListItem="true" FilterControlWidth="65px" HeaderStyle-Width="105px"/>
        <telerik:GridBoundColumn DataField="modelNumber" AllowFiltering="true" AllowSorting="true" HeaderText="Model Number" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Center" FilterControlWidth="95px" HeaderStyle-Width="135px" ItemStyle-Width="100px"></telerik:GridBoundColumn>
        <telerik:GridTemplateColumn DataField="notes" UniqueName="Notes" HeaderText="Notes"  Display="false" AllowFiltering = "false" FilterControlWidth="120px" HeaderStyle-Width="150px">
        <ItemTemplate>
            <%# Eval("notes") %>
        </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtNotes" Text='<%# Bind( "notes") %>' Columns="30" Rows="5"
                    TextMode="MultiLine" runat="server"></asp:TextBox>
            </EditItemTemplate>
        </telerik:GridTemplateColumn>
        <telerik:GridTemplateColumn DataField="comment" UniqueName="Comments" HeaderText="Comments" Visible="false" AllowFiltering = "false" FilterControlWidth="65px" HeaderStyle-Width="100px">
        <ItemTemplate>
            <%# Eval("comment") %>
        </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtComments" Text='<%# Bind( "comment") %>' Columns="30" Rows="5"
                    TextMode="MultiLine" runat="server"></asp:TextBox>
            </EditItemTemplate>
        </telerik:GridTemplateColumn>
 
        <telerik:GridBoundColumn DataField="serialNumber" AllowFiltering="true" AllowSorting="true" HeaderText="Serial Number" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Center" FilterControlWidth="95px" HeaderStyle-Width="135px" ItemStyle-Width="100px"></telerik:GridBoundColumn>
        <telerik:GridDropDownColumn UniqueName="DDLWho" DataSourceID="edsWho" SortExpression="name" ListTextField="name" ListValueField="id" HeaderText="User / Location" DataField="whoID" EnableEmptyListItem="true" EmptyListItemText="" HeaderStyle-HorizontalAlign="Center" FilterControlWidth="95px" HeaderStyle-Width="135px" ItemStyle-Width="100px"/>
        <telerik:GridDropDownColumn UniqueName="DDLStatus" DataSourceID="edsStatus" SortExpression="name" ListTextField="name" ListValueField="id" HeaderText="Status" DataField="statusID" EmptyListItemText="Choose a Status" EmptyListItemValue="" EnableEmptyListItem="true" HeaderStyle-HorizontalAlign="Center" FilterControlWidth="95px" HeaderStyle-Width="135px" ItemStyle-Width="100px"/>
        <telerik:GridCheckBoxColumn DataField="IPv6Compliant" AllowFiltering="false" AllowSorting="true" HeaderText="v6" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center"></telerik:GridCheckBoxColumn>
    </Columns>
 
</MasterTableView>
</ajci:JMGrid>
<asp:EntityDataSource runat="server" ID="edsAssetManager" EntitySetName="assets" ConnectionString="name=AssetTagManager"
    DefaultContainerName="AssetTagManager" EnableInsert="true" EnableDelete="true" Include="tag" OnInserting="MyEdsInserting" OnUpdating="MyEdsInserting"
    EnableUpdate="true" />
protected void MyEdsInserting(object sender, EntityDataSourceChangingEventArgs e)
{
     
    List<string> _error = new List<string>();
    AssetManager.FormException FormException = new AssetManager.FormException();
    AssetManagerDevModel.asset x = ((AssetManagerDevModel.asset)e.Entity);
    if (e.Exception is EntityDataSourceValidationException && e.Exception is System.Web.DynamicData.IDynamicValidatorException)
    {
        foreach (KeyValuePair<string, Exception> innerException in ((System.Web.DynamicData.IDynamicValidatorException)e.Exception).InnerExceptions)
        {
            _error.Add(innerException.Key + " is Blank");
        }
    }
    else
    {
        if (x.itemName == null)
            _error.Add("Name cannot be blank");
        if (x.tagID == null || x.tagID ==0)
            _error.Add("You must select a tag from the list");
        if (x.statusID  == 0)
            _error.Add("You must select an available status");
    }
 
    if (_error.Count > 0)
    {
        e.Cancel = true;
        e.ExceptionHandled = true;
        throw new Helper.DataInvalidException(_error);
    }
 
    else
    {
        x.modifyBy = HttpContext.Current.User.Identity.Name.Split('\\')[1];
        x.modifyDate = DateTime.Now;
    }
}

Thanks!

2 Answers, 1 is accepted

Sort by
0
Tsvetina
Telerik team
answered on 30 Dec 2011, 08:41 AM
Hello Jeremy,

My suggestion is to try using validation on the input values before you try to insert them into the datasource, instead of handling an exception which you know when would fire. Even with autogenerated editform, you could insert validators to prevent the user from trying to insert invalid data:
Validation

Other than this, without having a runnable project, I cannot tell you what needs to be done to fix the problemmatic behavior, having in mind that it happens as a result of a server exception, which could break different parts of the grid / datasource functionality.

Greetings,
Tsvetina
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
0
Jeremy
Top achievements
Rank 1
answered on 06 Jan 2012, 05:24 PM
Thank you for getting back to me.  i have changed to using client side validation but am struggling to find examples of how it is implemented with auto-generated forms.  The link provided did not show an example of that.  Here is a snippet of my item created event and the grid that it is supporting.

protected void GridItemCreated(object sender, GridItemEventArgs e)
{
    if (e.Item is GridEditableItem && e.Item.IsInEditMode)
    {
        GridEditableItem item = (GridEditableItem)e.Item;
        var DDLassetTagEditorControlID = item["DDLassetTag"].Controls[0].ID;
        var txtItemnameEditorControlID = item["txtAssetName"].Controls[0].ID;
        var ddlStatusEditorControlID = item["DDLStatus"].Controls[0].ID;
        RequiredFieldValidator StatusValidator = new RequiredFieldValidator();
        RequiredFieldValidator TagValidator = new RequiredFieldValidator();
        RequiredFieldValidator ItemNameValidator = new RequiredFieldValidator();
        TagValidator.ControlToValidate = DDLassetTagEditorControlID;
        TagValidator.ErrorMessage = "An asset tag is required";
        TagValidator.ValidationGroup = "ItemAssetValidators";
        (e.Item as GridEditableItem).Cells[1].Controls[0].Controls.AddAt(1, TagValidator);
 
        ItemNameValidator.ControlToValidate = txtItemnameEditorControlID;
        ItemNameValidator.ErrorMessage = "Please provide a name for the item";
        ItemNameValidator.ValidationGroup = "ItemAssetValidators";
        (e.Item as GridEditableItem).Cells[1].Controls[0].Controls.AddAt(1, ItemNameValidator);
 
        StatusValidator.ControlToValidate = ddlStatusEditorControlID;
        StatusValidator.ErrorMessage = "Please select a status for the item";
        StatusValidator.ValidationGroup = "ItemAssetValidators";
        (e.Item as GridEditableItem).Cells[1].Controls[0].Controls.AddAt(1, StatusValidator);
 }
}
 
 
 
protected void ValidateEditItem(object source, Telerik.Web.UI.GridCommandEventArgs e)
{
    if (e.CommandName == RadGrid.UpdateCommandName || e.CommandName == RadGrid.PerformInsertCommandName)
    {
        if (!Page.IsValid)
        {
            e.Canceled = true;
        }
    }
}
and now the grid
<ajci:JMGrid ID="ItemsGrid" runat="server" DataSourceID="edsAssetManager" AutoGenerateColumns="false" Skin="Windows7"
     AllowAutomaticInserts="true" AllowAutomaticDeletes="true" AllowAutomaticUpdates="false" DataKeyNames="id" OnUpdateCommand="GridOnUpdate" OnInsertCommand="GridOnInsert" EnableViewState="true" OnItemCreated="GridItemCreated" OnItemCommand="ValidateEditItem">
    <ExportSettings IgnorePaging="true" OpenInNewWindow="true" ExportOnlyData="true"
        FileName="AssetList">
        <Excel Format="Html" FileExtension="xls" />
    </ExportSettings>
    <MasterTableView EditMode="PopUp" AllowFilteringByColumn="true" CommandItemDisplay="Top"
        CommandItemSettings-AddNewRecordText="Add Items" DataKeyNames="id" TableLayout="Fixed">
        <EditFormSettings CaptionFormatString="Add/Edit Item" PopUpSettings-Modal="true" EditFormType="AutoGenerated">
    </EditFormSettings>
 
    <CommandItemTemplate>
        <asp:LinkButton runat="server" ID="lnkAdd" Text="Add Item" CssClass="iconAdd" CommandName="InitInsert" ></asp:LinkButton>
        <asp:LinkButton ID="btnManualRefresh" CssClass="iconRefresh" runat="server" Text="Refresh Data" OnCommand="GridRefresh" />
        <asp:LinkButton ID="ExportToExcelButton2" runat="server" OnClick="ExportData" CommandArgument="Excel" Text="Export To Excel" CssClass="buttonExcel" />
    </CommandItemTemplate>
    <Columns>
        <telerik:GridTemplateColumn AllowFiltering="false" ItemStyle-Width="100px" HeaderStyle-Width="100px" ReadOnly="true">
            <ItemTemplate>
                <div>
                    <asp:LinkButton ID="btnEdit" CommandName="Edit" runat="server"  CssClass="iconEdit" Text=" "></asp:LinkButton>
                    <asp:LinkButton ID="lbDeleteRecord" runat="server" CssClass="iconDelete" Text=" " CommandName="Delete" CommandArgument='<%# Eval("id") %>' OnClientClick="javascript:return confirm('Removing this item will also clear its related history.  Continue?')"></asp:LinkButton>
                    <a href="#" onclick="openRadWindow('<%#DataBinder.Eval(Container.DataItem,"id") %>'); return false;">
                        <img src="../Assets/images/icons/icon-magnifying-glass.png" />
                    </a>
                     
                    <asp:Image ID="imgNote" runat="server" ImageUrl="../Assets/images/icons/icon-notes.png" />
                    <telerik:RadToolTip ID="tooltpNotes" runat="server" TargetControlID="imgNote" RelativeTo="Element"
                        Position="BottomCenter" RenderInPageRoot="true" ManualClose="true">
                        <p></p>
                        <div>
                            <asp:Label id="ttpAssetNote" runat="server" Text='<%# Eval("notes")%>'></asp:Label>
                        </div>
                    </telerik:RadToolTip>
 
                    <asp:Image ID="imgComment" runat="server" ImageUrl="../Assets/images/icons/icon-comment.png" />
                    <telerik:RadToolTip ID="tooltpComment" runat="server" TargetControlID="imgComment" RelativeTo="Element"
                        Position="BottomCenter" RenderInPageRoot="true" ManualClose="true">
                        <p></p>
                        <div>
                            <asp:Label id="ttpAssetComment" runat="server" Text='<%# Eval("comment")%>'></asp:Label>
                        </div>
                    </telerik:RadToolTip>
                    <asp:Image ID="imgQRTag" runat="server" CssClass="iconQR" ImageUrl='<%# AssetManager.Helper.QRImage.GetQRIMageURL(Eval("tag.assetTag").ToString()) %>' />
                    <telerik:RadToolTip ID="tltpQRStatus" runat="server" TargetControlID="imgQRTag"
                    RelativeTo="Element" Position="BottomCenter" RenderInPageRoot="true" EnableShadow="true"
                    ManualClose="true">
                        <div >
                            <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# AssetManager.Helper.QRImage.GetQRIMageURL(Eval("tag.assetTag").ToString()) %>' Target="_blank" Text="Asset QR Code"/>
                        </div>
                        <div id="RenderedQR">
                            <asp:Image ID="qrImage" runat="server" ImageUrl='<%# AssetManager.Helper.QRImage.GetQRIMageURL(Eval("tag.assetTag").ToString()) %>'
                                Title='<%# Eval("tag.assetTag") + ".png" %>' ClientIDMode="Static"/>
                        </div>
                        <div>
                            <asp:Label ID="lblQRAssetID" runat="server" Text='<%# Eval("tag.assetTag") %>'></asp:Label>
                        </div>
                    </telerik:RadToolTip>                    </div>
            </ItemTemplate>
        </telerik:GridTemplateColumn>
        <telerik:GridDropDownColumn  UniqueName="DDLassetTag" DataSourceID="edsAssetTag" SortExpression="assetTag" ListTextField="assetTag" ListValueField="id" HeaderText="AssetTag" DataField="tagID" EmptyListItemText="Choose an Asset Tag" EmptyListItemValue="" EnableEmptyListItem="true" HeaderStyle-HorizontalAlign="Center" FilterControlWidth="95px" HeaderStyle-Width="135px" ItemStyle-Width="100px"/>
       <telerik:GridBoundColumn UniqueName="txtAssetName" DataField="itemName" AllowFiltering="true" AllowSorting="true" HeaderText="Item Name" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Center" FilterControlWidth="120px" HeaderStyle-Width="160px"></telerik:GridBoundColumn>
        <telerik:GridDropDownColumn UniqueName="DDLManufacturer" DataSourceID="edsManufacturer" SortExpression="mfgName" ListTextField="mfgName" ListValueField="id" HeaderText="Manufacturer" DataField="mfgID" EmptyListItemText="Choose a Manufacturer" EmptyListItemValue="" EnableEmptyListItem="true" FilterControlWidth="65px" HeaderStyle-Width="105px"/>
        <telerik:GridBoundColumn DataField="modelNumber" AllowFiltering="true" AllowSorting="true" HeaderText="Model Number" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Center" FilterControlWidth="95px" HeaderStyle-Width="135px" ItemStyle-Width="100px"></telerik:GridBoundColumn>
        <telerik:GridTemplateColumn DataField="notes" UniqueName="Notes" HeaderText="Notes"  Display="false" AllowFiltering = "false" FilterControlWidth="120px" HeaderStyle-Width="150px">
        <ItemTemplate>
            <%# Eval("notes") %>
        </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtNotes" Text='<%# Bind( "notes") %>' Columns="30" Rows="5"
                    TextMode="MultiLine" runat="server"></asp:TextBox>
            </EditItemTemplate>
        </telerik:GridTemplateColumn>
        <telerik:GridTemplateColumn DataField="comment" UniqueName="Comments" HeaderText="Comments" Visible="false" AllowFiltering = "false" FilterControlWidth="65px" HeaderStyle-Width="100px">
        <ItemTemplate>
            <%# Eval("comment") %>
        </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtComments" Text='<%# Bind( "comment") %>' Columns="30" Rows="5"
                    TextMode="MultiLine" runat="server"></asp:TextBox>
            </EditItemTemplate>
        </telerik:GridTemplateColumn>
 
        <telerik:GridBoundColumn DataField="serialNumber" AllowFiltering="true" AllowSorting="true" HeaderText="Serial Number" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Center" FilterControlWidth="95px" HeaderStyle-Width="135px" ItemStyle-Width="100px"></telerik:GridBoundColumn>
        <telerik:GridDropDownColumn UniqueName="DDLWho" DataSourceID="edsWho" SortExpression="name" ListTextField="name" ListValueField="id" HeaderText="User / Location" DataField="whoID" EnableEmptyListItem="true" EmptyListItemText="" HeaderStyle-HorizontalAlign="Center" FilterControlWidth="95px" HeaderStyle-Width="135px" ItemStyle-Width="100px"/>
        <telerik:GridDropDownColumn UniqueName="DDLStatus" DataSourceID="edsStatus" SortExpression="name" ListTextField="name" ListValueField="id" HeaderText="Status" DataField="statusID" EmptyListItemText="Choose a Status" EmptyListItemValue="" EnableEmptyListItem="true" HeaderStyle-HorizontalAlign="Center" FilterControlWidth="95px" HeaderStyle-Width="135px" ItemStyle-Width="100px"/>
        <telerik:GridCheckBoxColumn DataField="IPv6Compliant" AllowFiltering="false" AllowSorting="true" HeaderText="v6" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center"></telerik:GridCheckBoxColumn>
    </Columns>
 
</MasterTableView>
</ajci:JMGrid>
Tags
Grid
Asked by
Jeremy
Top achievements
Rank 1
Answers by
Tsvetina
Telerik team
Jeremy
Top achievements
Rank 1
Share this question
or