Thursday, March 22, 2012

simple dropdownlist selected item question

hi. i am populating contents of a DDL then setting selected item as so:

ddlTitle.DataSource = myDataTable;
ddlTitle.DataTextField = "title";
ddlTitle.DataValueField = "defaultsex";
ddlTitle.DataBind();
ddlTitle.SelectedItem.Text = "M";

but dropdownlist showing "M" value twice both at top of list and in its correct alphabetical position. If I select a different DDL item e.g. "Mrs" then "M" is still shwoing twice. I want "M" to be selected item but only appear once in list in its correct alphabetical position.HI
Dim ss As ListItem
ss = ddlTitle.Items.FindByValue("M")
ddlTitle.SelectedIndex = ddlTitle.Items.IndexOf(ss)
Try setting the selected item by the index of M. If you load M in as the third value use:

ddlTitle.SelectedItem.Index = 3

Hope this helps.

- Jesse Williams
What you are doing here is changing the text value of whatever item is already selected. In order to set the selecteditem to whatever you want you can either use the SelectedValue or SelectedIndex properties which matches the value and index respectively.

Example;

ddlTitle.SelectedValue = "M"; // or whatever the value of "M"
ddTitle.SelectedIndex = 2; // or whatever is the index value of "M"

However if you only know the text of the ListItem it is still possible to select it.

Use something like this:

ddTitle.Items.FindByText("M").Value ;

hope this does the trick,

sivilian
thanks this worked for me:


ListItem li = ddlTitle.Items.FindByText("M");
ddlTitle.SelectedIndex = ddlTitle.Items.IndexOf(li);

0 comments:

Post a Comment