How to set DropDownList's selected value inside a Repeater?
Solution 1
Maybe I'm misunderstanding something about your question... but it seems like this is exactly what OnItemDataBound is for. :)
Use FindControl to get a reference to your DropDownList in the event handler. Also check to make sure the item is not the header/footer. The example from MSDN does both these things:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.onitemdatabound.aspx
Solution 2
In regard the problem I specified in my edit, the time of the DataBind
plays an important role. I used to do the databinding in the Page_Init
event, which caused the repeater_ItemDataBound
event to be fired before the button_OnClick
event.
The solution was to move the databinding to the Page_PreRender
event.
The population of the DropDownList
with all the choises is still done in its OnInit
event.
vipirtti
Updated on February 24, 2020Comments
-
vipirtti about 4 years
I need to create a group of
DropDownList
s to show and allow change of a property group for an item.I have the following code on my ASP page.
<asp:Repeater runat="server" ID="repeaterProperties"> <ItemTemplate> <p><asp:DropDownList runat="server" ID="ddProperty" OnInit="ddProperty_OnInit" /><p> </ItemTemplate> </asp:Repeater>
The
ddProperty_OnInit
populates theDropDownList
with all the possible values with a database query.How can I set the selected value of each created
DropDownList
according to theRepeater
's source data?Let's say, for example, that we have the possible property values of
A
,B
andC
.
If the database output for theRepeater
contains two of those values,A
andB
, theRepeater
outputs twoDropDownList
s, both with all 3 values availabla and the first one withA
as selected value and the second one withB
as selected value.Edit:
It seems that addingOnItemDataBound="repeater_ItemDataBound"
to theRepeater
and selecting the appropriate value in there is not the way to go in my case. This is because I also need to save the possibly changed values to a database.The
ItemDataBound
event of theRepeater
is fired before theOnClick
event on aButton
and changes the selected values to their old values before the new selections can be saved.Any suggestion on how to work around this?
Current code:
<asp:Repeater runat="server" ID="repeaterJako" OnItemDataBound="repeater_ItemDataBound"> <ItemTemplate> <asp:DropDownList id="ddJako" runat="server" OnInit="ddJako_OnInit"> </asp:DropDownList><br /> </ItemTemplate> </asp:Repeater> <asp:Button runat="server" id="updateButton" Text="Save" OnClick="update_OnClick" />
In the code-behind,
ddJako_OnInit
populates the drop down list with all the possible choises, while therepeater_ItemDataBound
uses the method suggested by Bryan Parker to select the proper value. -
vipirtti about 15 years@jwalkerjr I did, untill I found out that it did not help my situation. Well, I did figure it out just a minute ago, so might as well. It's a good answer and mine will only add to it.