views:

383

answers:

1

Please note that the problem described below is almost the exact opposite to the common problem of "my control shows the same value every time the page loads. I understand the behavior expressed is generally not desirable.

I have a listbox which is being databound in the page load event even on postback.

When the event handler for the selectedindex changed is hit, the control somehow has the posted value even though it has already been bound again and should not have a selectedindex at this point.

Does anyone know how this could be possible.

EDIT:

To demonstrate that the SelectedIndex is indeed reset you can create a form with the following simple markup:

    <label for="textbox1">Original Posted Value: </label>
    <asp:TextBox runat="server" ID="textbox1" />
    <asp:DropDownList runat="server" ID="dropdown" OnSelectedIndexChanged="dropdown_SelectedIndexChanged" AutoPostBack="true" />
    <label for="textbox2">Value at point handler is hit: </label>
    <asp:TextBox runat="server" ID="textbox2" />

With the following code in the .cs

        protected void Page_Load(object sender, EventArgs e)
    {
        textbox1.Text = dropdown.SelectedIndex.ToString();
        dropdown.DataSource = new string[] { "none", "A", "B", "C" };
        dropdown.DataBind();
    }
    protected void dropdown_SelectedIndexChanged(object sender, EventArgs e)
    {
        textbox2.Text = dropdown.SelectedIndex.ToString();
    }

Notice that the value in the second textbox will alway be 0.

+1  A: 

The problem here is that the datasource is getting re-assigned and re-bound on each page load including postbacks. The selected index is changed and then changed back to 0. Try cathcing the postbacks, and only set the datasource if it is not a postback (the initial load) such as this in the .cs

protected void Page_Load(object sender, EventArgs e)

    {
        if (Page.IsPostBack)
        {
            textbox1.Text = dropdown.SelectedIndex.ToString();
        }
        else
        {
            dropdown.DataSource = new string[] { "none", "A", "B", "C" };
            dropdown.DataBind();
        }
    }

    protected void dropdown_SelectedIndexChanged(object sender, EventArgs e)
    {
        textbox2.Text = dropdown.SelectedIndex.ToString();
    }
Tom Willwerth