Tomasz Iniewicz
Tomasz Iniewicz

Reputation: 4469

.NET DropDownList postback selection won't select anything but first <option>

I'm having this problem with a .NET DropDownList control.

PROBLEM: Every time I do a postback, It just defaults to the same first option tag as the one selected. I can't seem to get it so that it is pointing to the actual selected <option>.

Basically, here is what is happening.

1 . I make a DropDownList control in Default.aspx

<asp:DropDownList ID="controlSelector" AutoPostBack="true" 
    OnSelectedIndexChanged="onSelectChange" runat="server" />

2 . I pull data from a database

DevHTMLGetter getControls = new DevHTMLGetter();

DataTable queryResult = new DataTable();
queryResult = getControls.getControlNames("getAdminHTML");

// binds the DataTable to the DropDownList
controlSelector.DataTextField = "controlName";
controlSelector.DataValueField = "controlID";
controlSelector.DataSource = queryResult;
controlSelector.DataBind();

The data is:

    ---------------------------
    | CONTROLID | CONTROLNAME |
    ---------------------------
    |    1      | testcontrol |
    ---------------------------
    |    2      | tstcontrol2 |
    ---------------------------

3 . I than try to manipulate the data when the form is submitted:

protected void displayControlsHTML(Object sender, EventArgs
{
    String selectedItem = controlSelector.Attributes["selected2"].ToString();
    String n = controlSelector.Items.FindByText(selectedItem).ToString();

    DevHTMLGetter getControls = new DevHTMLGetter();
    Dictionary<String, String> displayItems = 
        getControls.getControlsForEdit("getSpecificControlItems", selectedItem); 
        // from Web.Config <AppSettings>

    //sets all of the boxes to their appropriate text
    txtControlName.Text = displayItems["controlName"].ToString();
    txtControlClassName.Text = displayItems["className"].ToString();
    txtLiveHTMLEditBox.Text = displayItems["controlHTML"].ToString();
    txtDisplayHTMLEditBox.Text = displayItems["displayHTML"].ToString();
}

My page renders like so:

<select class="myDropDown" id="ctl00_defaultContent_controlSelector" name="ctl00$defaultContent$controlSelector">
    <option value="1" selected="selected">Test Control</option>
    <option value="2">Test Control2</option>
</select>

NOTE: onSelectChange, the event on the DropDownList control doesn't do anything because I submit it with a SUMBMIT button.

Upvotes: 1

Views: 1416

Answers (1)

Craig
Craig

Reputation: 4383

Sounds like you're probably re-databinding the dropdown on postback.

Try wrapping an if (!PostBack) { ... } statement around your databinding code:

    if (!IsPostBack)
    {
        controlSelector.DataTextField = "controlName";
        controlSelector.DataValueField = "controlID";
        controlSelector.DataSource = queryResult;
        controlSelector.DataBind();
    }

Upvotes: 4

Related Questions