I have a feeling I'm missing something really obvious, I'm not able to capture the selected value of my DropDownList; the value renaubs the first item on the list. I have set the DropListList autopostback property to true. I have a SelectedIndexChangedEvent which is pasted below. This is NOT on the master page.
protected void ddlRestCity_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
r_city = ddlRestCity.SelectedValue.ToString();
}
}
Here is the DropDownList control:
<asp:DropDownList ID="ddlRestCity" runat="server"
Width="100px" AutoPostBack="True"
onselectedindexchanged="ddlRestCity_SelectedIndexChanged">
</asp:DropDownList>
Thanx in advance for your help!
You have to use SelectedValue property of DropDownList . DataTextField and DataValueField are for specifying which properties from DataSource should be used as Text and Value of drop down list. Save this answer.
The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.
In order to be able to select an item and have the value updated to the database, in the DropDownList add the AutoPostBack property and set it to true. Then, add the OnSeletedIndexChanged property and choose the 'create new event' option. It will created a method automatically in the <filename>. aspx.
My off the cuff guess is you are maybe re-populating the list on a post back and that is causing the selected index to get reset.
Where is your DataBind()
call? Are you checking !IsPostBack
before the call? For example:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
ddlRestCity.DataSource = ...;
ddlRestCity.DataBind();
}
}
Explanation: If you don't check for !IsPostBack
before DataBind()
, the list will re-populate before SelectedIndexChanged
is fired (because Page.Load
fires before child events such as SelectedIndexChanged
). When SelectedIndexChanged
is then fired, the "selected item" is now the first item in the newly-populated list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With