次の方法で共有


ASP.NET 2.0 - Cannot find control in EditItemTemplate of DetailsView Control

Recently we got some cases in ASP.NET 2.0, where customers were using: -

- DetailsView control bound with SQL Data source control.

- DetailsView has few Data-bound Columns as well as one Template Column.

- Data bound columns displays correct values.

- However, there are some issues with Templated Column that looks like:

<asp:TemplateField HeaderText="BusinessOrgName" SortExpression="BusinessOrgName">

<EditItemTemplate>

    <asp:ListBox ID="LstBUOrg" runat="server" AutoPostBack="true" DataSourceID="BUOrgDataSource"

        DataTextField="BusinessOrgName" Width="347px" DataValueField="BusinessOrgID" SelectionMode="Multiple" SelectedValue='<%# Bind("BusinessOrgID") %>'>

    </asp:ListBox>

    </EditItemTemplate>                                                                   

<ItemTemplate>

    <asp:Label ID="LblBOrg" runat="server" Text='<%# Bind("BusinessOrgName") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

- Most of the time, Template Column works fine but with one exception. Exception is, when Label control inside <ItemTemplate> is blank. As a result, when user switches to DetailsView Edit mode, where SelectedValue property of the ListBox control is used, we get error stating "Value that we are trying to select is not present in the Listbox Items”, which is basically a NULL value.

Now how to avoid this situation to happen?

RESOLUTION

==========

- To get rid of this situation, some of the customers were trying to get the reference of the ListBox control, as soon as the Label is blank so that they can change the SelectedValue property dynamically.

- That seems to be a good idea, but the events like (ModeChanged/ModeChanging) where they want to get this job done are not appropriate.

- This is because; we cannot get the Listbox reference under ModeChanged/ModeChanging events as Listbox control under <EditItemTemplate> is still not built at this time.

- We will get the reference of Listbox control inside ItemUpdated(ItemUpdating) event that will be called while Updating the DetailsView control. But for the above situation, that we will too late because we will get the error as soon as user switches to edit mode with a blank label.

- Only way left is to implement OnPreRender event for Listbox control inside <EditItemTemplate> where SelectedValue property is set to null if the Label is blank.

To learn more about DetailsView control, visit the following link:

https://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/detailsview.asp

Hope this helps!! Please feel free to send me an email if you have any questions.