Monday, March 26, 2012

Setting selected item in DDL on page load?

I'm populating a dropdownlist from an Access table, and would like to know how I can select a certain item in that list by default. The page knows the value of the item that should be selected, I'm just having issues figuring out how to sync things up.

ex. How would "Option 2" be selected (programatically -- C#) by default on the initial page load?

DDL:


<asp:DropDownList Runat=server ID=ddlList DataTextField=this DataValueField=that>
<asp:ListItem Value="OptionA">Option 1</asp:ListItem>
<asp:ListItem Value="OptionB">Option 2</asp:ListItem>
<asp:ListItem Value="OptionC">Option 3</asp:ListItem>
</asp:DropDownList>

Thanks,
-DC RossIn page_load you can say


ddlList.SelectedIndex = 1;

This will select "Option 2".
Thanks, but unfortunately, I don't know exactly where "Option 2" will be in the list. All I do know is the value & text.


ddlList.SelectedValue = "OptionB";

Thanks, Sharbel, but I'm not finding a "SelectedValue" property of a DropDownList...
Oh yeah, it is a Framework 1.1 property, so you do have to have 1.1 installed.
I could find a SelectedItem property of the ListBox control, is this the same thing as a DropDownList? If so, why would MS give us two similar controls?

Thanks again
Actually, I was wrong, the ListBox I was looking at was a Windows control, not a Web control. There was no SelectedValue property of the System.Web.UI.WebControls.ListBox in 1.1.
You could iterate through the list, comparing each value to the value you're looking for - if it's equal, select that index.

for (int i=0; i<DDList.Items.Count; i++)
{
if (DDList.Items[i].Value == "Option 2")
{
DDList.SelectedIndex = i;
}
}
Can this be something for You??

cboMainMenu.Items.FindByValue(dr["menuField"].ToString()).Selected=true;
Umm yes there is a .SelectedValue property in the v1.1 DropDownlist.. i use it all the time ... there is another thread saying there isnt too, am I the only one with the property or something ?? :)
They're wrong, your right. ;)

System.Web.UI.WebControls.DropDownList.SelectedValue
Damn, I thought MS loved me more or something and gave me an extra property :(
DropDownList is derived fromListControl, which defines theSelectedItem property.
m'kay, now I'm really confused... I definitely have v.1.1.4322 installed, and when I try building the solution, I get the error: "'System.Web.UI.WebControls.DropDownList' does not contain a definition for 'SelectedValue'"

0 comments:

Post a Comment