views:

281

answers:

1

Hi, 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 .

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 submited

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

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

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

+3  A: 

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();
    }
Craig
i knew I was missing something. Thanks!
Tomaszewski