DropDownList in FormView binding

markiz picture markiz · May 24, 2009 · Viewed 21.9k times · Source

I want to bind dropdownlist to List<MyIem>, in code behind.

 <asp:DropDownList ID="listCategories"  runat="server" Height="20px"   CssClass="CategoryDropList" SelectedValue='<%# Bind("ParentId") %>' AutoPostBack="false" Width="300px">      

Without using ObjectDataSource !

How can I Bind it to the dropdown list? In what event?

Also SelectedValue='<%# Bind("ParentId") %>' should work! (I mean the dropdownlist binding should occur before this!)

Answer

Kb. picture Kb. · May 24, 2009

Made an example which will set the dropdown in the DataBound event.
Here is the markup
The way to use the ddl, is to find it with findcontrol() during DataBound event.
When you have the control in the DataBound event, you can also bind the dropdown to your List<>
Hope this helps.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>

        </div>
        <asp:FormView ID="FormView1" runat="server" ondatabound="FormView1_DataBound">
            <ItemTemplate>
                <asp:DropDownList ID="DropDownList1" runat="server">
                    <asp:ListItem>One</asp:ListItem>
                    <asp:ListItem>Two</asp:ListItem>
                    <asp:ListItem>Three</asp:ListItem>
                </asp:DropDownList>

            </ItemTemplate>
        </asp:FormView>
        </form>
    </body>
    </html>

Here is the code behind:

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            list.Add("Some");
            list.Add("Other");

            FormView1.DataSource = list; //just to get the formview going

            FormView1.DataBind(); 

        }

        protected void FormView1_DataBound(object sender, EventArgs e)
        {
            DropDownList ddl = null;
            if(FormView1.Row != null)
                ddl = (DropDownList) FormView1.Row.FindControl("DropDownList1");
            ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue("Two"));
        }
    }
}