C# – Selected value of dropdownlist in repeater control – with predefined items

asp.netc

I have a DropDownList inside a repeater control in an ASP.NET page that has predefined items. How would I go about setting the selected value of it after binding the data to the repeater 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>

Because the DropDownList control doesn't have a SelectedValue front-end property, I can't set it on the control level. Instead you have to use the selected property of the list item. What would be ideal is:

<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>

Unfortunately that won't work, any ideas?

Best Answer

Using the code from Pankaj Garg (thank you!) I've managed to write up the method to select the correct value. I couldn't mark it as the answer as that answer is selecting a static value, but not one that is 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 everybody who helped out.

Related Topic