Changing the DropDownList Selected Item via a Property

G

g

I have a user control that contains a dropdownlist. Using a public
property, I can get the selected item. However, I am unsure of how to use
that same public property to set the selected item. Here's my code:

private string m_item = "";

public string Item
{
get
{
m_item = this.dropdownlist.SelectedValue;
return m_item;
}
set
{
m_item = value;
// How to set the selected value/item in the dropdownlist
this.dropdownlist.SelectedValue = m_item; // Doesn't work...
}
}
 
N

Nathan Sokalski

My recommendation would be to use the SelectedIndex property. If you cannot
find a way to use this and setting the SelectedValue property gives you
problems, try this:

DropDownList1.SelectedIndex =
DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue("valuetoselect"))


I don't know why they would act any different, but for some reason I have
come to trust the SelectedIndex property more. One other thing I would
suggest you be careful about is the fact that you are using the class name
'dropdownlist' as your Control ID. It is usually a bad idea to use class
names as IDs, and could sometimes return an error. Does your code return an
error when you try to set the SelectedValue? If so, it would be a good idea
to share the error message/info in the newsgroup postings.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top