I have a user control that contains a repeater. The repeater contains some control, including a dropDownList with id ‘ddlPallet’. The repeater is bound to a dataset in the user controls’ Page_Load event.
I’m using the ItemDataBound event of the repeater to change the SelectedValue of the dropdownlist based on a value from the dataset.
The problem I’m having is that when the page renders, ALL of the dropdownlists’ selectedValue are set to the last selectedValue specified – i.e. If there are 8 rows in the dataset and row 8 is ‘N’ then the selected index of all instances of ‘ddlPallet’ will have a selectedValue of ‘N’
Here’s my ItemDataBound code:
Protected Sub rptCavities_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptCavities.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim ddl As DropDownList
ddl = e.Item.FindControl("ddlPallet") 'get the dropdown
ddl.Items.AddRange(Me._arrPallets) 'add items
Dim drv As DataRowView = CType(e.Item.DataItem, DataRowView) 'get the data row being bound
Dim sv As String = "" 'get the value of the 'pallet' column from the dataset
If Trim(drv("Pallet").ToString()) <> "" Then
sv = drv("Pallet").ToString()
Else
sv = "N"
End If
ddl.SelectedValue = sv 'set the selected value of the dropdown list for this item
'debug
System.Diagnostics.Debug.WriteLine("----")
System.Diagnostics.Debug.WriteLine("Control ID: " & ddl.ID)
System.Diagnostics.Debug.WriteLine("Control Client ID: " & ddl.ClientID)
System.Diagnostics.Debug.WriteLine(ddl.SelectedIndex.ToString() & " - " & ddl.SelectedItem.ToString() & " - " & ddl.SelectedValue)
System.Diagnostics.Debug.WriteLine("")
End If
End Sub
The debug output shows that the appropriate SelectValue is being set per item/per dropDownList:
Control ID: ddlPallet
Control Client ID: Cure1_rptCavities_ctl01_ddlPallet
4 – FL – FL
Control ID: ddlPallet
Control Client ID: Cure1_rptCavities_ctl02_ddlPallet
3 – EP – EP
Control ID: ddlPallet
Control Client ID: Cure1_rptCavities_ctl03_ddlPallet
0 – N – N
..etc.
This is driving me nuts. I assume I have some kind of scoping error that is causing the last-set index value to apply to all instances of the dropDownList in the repeater, but I’m having no luck figuring out where or why. If I bind the same data to a label in the ASCX file using “Text='<%#Container.DataItem(“Pallet”)%>'” the correct data is displayed.
It may be because you’re adding the same items to the drop down list in every case, rather than binding the dropdownlist to the source data. This way, they all share a common set of items, and if you set Selected = true to one item, it’ll be true for every dropdownlist that contains that item.
Potentially an interesting technique, but probably not what you want.