Click here to Skip to main content
15,890,690 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,
my case is that i want to write a code to change the selected value of the dropdownlist actually i have 2 values (True, False).
I tried

C#
SolvedDropDownList.SelectedItem.Text = solved;


but it's making the both options False...
i thought i did it wrong coz i have to change the selected item not the text of the selected item.. but i dont know how to do it.. please could someone help me...


[Edit] Added Code Snippet [/Edit]
Posted
Updated 29-Dec-10 1:45am
v2
Comments
Hiren solanki 30-Dec-10 12:54pm    
Comment from velmahesh : Hi shadi_abushaar,

did u use the AutoPostback =true ?.. in aspx page

As you said, SelectedItem is read-only. But, SelectedValue is not.

If you have two items in your dropdownlist with string values of "True" and "False", then you just set the SelectedValue property as in

C#
SolvedDropDownList.SelectedValue = solved;


But that does depend on what solved is and what is contained in the items in your dropdownlist.

If you did this:
C#
SolvedDropDownList.Items.Add(true);
SolvedDropDownList.Items.Add(false);

it would add two items with the string representations of true and false.

Then, if solved was a boolean you should be fine.
 
Share this answer
 
Comments
fjdiewornncalwe 29-Dec-10 16:02pm    
Well explained...
Suppose the value of your true and false is 1 and 2 respectively. (To check this, see the source code of drop down when the page is rendered)

C#
//SolvedDropDownList.SelectedItem=1 //for true

//SolvedDropDownList.SelectedItem=2 //for false

SolvedDropDownList.SelectedValue=1 //for true

SolvedDropDownList.SelectedValue=2 //for false




I hope you got the nerve.

Anurag
 
Share this answer
 
v2
Comments
Hiren solanki 29-Dec-10 8:00am    
Good answer anurag.
@nuraGGupta@ 29-Dec-10 8:03am    
Thanks. :-)
shadi_abushaar 29-Dec-10 8:19am    
but that's not the way cz SolvedDropDownList.SelectedItem is read only that means you can't assign values to it.. i tried this also...
William Winner 29-Dec-10 13:31pm    
SelectedItem is read-only
fjdiewornncalwe 29-Dec-10 16:03pm    
This simply won't work. See William's answer above for the correct solution.
//Clear the previously selected values
SolvedDropDownList.ClearSelection();

//Iterate through all the items and selected the one you want.
foreach(ListItem item in SolvedDropDownList.Items)
{
if (item.Value == solved)
{
item.Selected = true;
break;
}
}

Hope this helps.
Tajinder Sarao
 
Share this answer
 
Comments
fjdiewornncalwe 29-Dec-10 16:03pm    
Highly inefficient way of doing this. See William's answer for the solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900