asp .net dropdownlist selectedindex not working

Varun Sharma picture Varun Sharma · Aug 30, 2011 · Viewed 15.9k times · Source

I have the following piece of code:

DataRow CreateRow(DataTable dt, string name, string country)
    {
        DataRow dr = dt.NewRow();
        dr["Name"] = name;
        dr["Country"] = country;
        return dr;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // creating the data table
        DataTable dt = new DataTable("Student Details");

        // adding two columns Name and Country
        dt.Columns.Add("Name", typeof(String));
        dt.Columns.Add("Country", typeof(String));

        // create 3 rows        
        dt.Rows.Add(CreateRow(dt, "Varun", "India"));
        dt.Rows.Add(CreateRow(dt, "Li", "China"));
        dt.Rows.Add(CreateRow(dt, "Yishan", "China"));

        // create a data view 
        DataView dv = new DataView(dt);

        DropDownList1.DataSource = dv;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "Country";
        DropDownList1.DataBind();
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int x = DropDownList1.SelectedIndex;
        int temp = 0;
        temp++;
    }

and the markup looks like this:

<body>
    <form id="form1" runat="server">
    <div>

        <asp:Label ID="Label1" runat="server"></asp:Label>
        <br />
        <br />
        <asp:DropDownList ID="DropDownList1" runat="server" 
            onselectedindexchanged="DropDownList1_SelectedIndexChanged"
            AutoPostBack="true">
        </asp:DropDownList>

    </div>
    </form>
</body>

The problem is that label is always showing Varun no matter what I select. I debugged the code and found out that "DropDownList1.SelectedIndex" is always returning 0 for some reason.

I am not sure why is this happening. The function "DropDownList1_SelectedIndexChanged" is getting called every time I select something from the drop down list.

Thanks

Answer

c0deNinja picture c0deNinja · Aug 30, 2011

Looks like you are binding the drop down in the Page_Load...

Remember that when the drop down is changed, it does a post back (AutoPostBack='True'), and since you are binding on Page_Load it will simply rebind ever time the index is changed... not what you want!

you should do something like this:

if (!IsPostBack)
{  
    BindDropDownList1();      
}