Selected dropdown value in repeater control - with predefined items
I have a DropDownList inside a relay control in an ASP.NET page with predefined elements. How can I set the selected value after data binding to the relay control?
For example, I have this code:
<asp:DropDownList ID="cboType" runat="server">
<asp:ListItem Text="Communication" Value="Communcation" />
<asp:ListItem Text="Interpersonal" Value="Interpersonal" />
</asp:DropDownList>
Since the DropDownList control does not have a front-end SelectedValue property, I cannot set it at the control level. Instead, you should use the selected property of the list item. Ideally it would be:
<asp:DropDownList ID="cboType" runat="server" SelectedValue='<%# Eval("Type_Of_Behavior") %>'>
<asp:ListItem Text="Communication" Value="Communcation" />
<asp:ListItem Text="Interpersonal" Value="Interpersonal" />
</asp:DropDownList>
Sorry it doesn't work, any ideas?
source to share
Using Pankaj Garg's code (thanks!) I was able to write a method to pick the correct value. I couldn't mark this as an answer, as this answer is picking a static value, but not the one coming from the DB. Here's the function:
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList cbo = (DropDownList)e.Item.FindControl("cboType");
Behaviour b = (Behaviour)e.Item.DataItem;
for (int i = 0; i < cbo.Items.Count; i++)
{
if (b.Type_of_Behaviour == cbo.Items[i].Value)
cbo.Items[i].Selected = true;
else
cbo.Items[i].Selected = false;
}
}
}
Thanks to everyone who helped.
source to share
In Runtime, you can use a
OnItemDataBound
repeater as shown below.
Example HTML
<asp:Repeater ID="rpt" runat="server" OnItemDataBound="YourhandlerName" >
</asp:Repeater>
Sample Code for OnItemDataBound
Event Handler
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList DropDownID = (DropDownList)e.Item.FindControl("DropDownID");
int ItemNo = ((YourClassName)e.Item.DataItem).Yourproperty;
DropDownID.Items[ItemNo].Selected = true;
}
}
source to share