SelectedValue in dropdownlist - invalid item but no exception

J

John

If you set DropDownList.SelectedValue to an item not in the list, shouldn't
an exception be thrown? ie:

<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
</asp:DropDownList>

Then in the codebehind:

DropDownList1.SelectedValue = "999";

No exception is thrown, but the docs say:

"The SelectedValue property can also be used to select an item in the list
control by setting it with the value of the item. If no items in the list
control contain the specified value, a System.ArgumentOutOfRangeException is
thrown."

XP Pro sp2. ASP.NET 2.0 (VS2005 Team Edition for Soft Devs). C# 2.0. All the
latest updates.

Thanks,

John
 
Joined
May 16, 2006
Messages
27
Reaction score
0
It should throw an exception, like as follow,

Specified argument was out of the range of valid values. Parameter name: 999

are you writing your code in try catch?
 
J

John

PS. I have the June 06 CTP of Atlas installed (but the problem also occurs
in apps that don't use Atlas)
 
Joined
Jun 25, 2008
Messages
2
Reaction score
0
Same Issue

I'm trying to rely on an exception being thrown to set a catch-all "other" value.

I'm also not getting the expected exception - I am using .net 2.0 with the asp.net ajax 1.0 extensions installed.

I'm going to try a workaround using ddl.Items.FindByValue()
 
Joined
Jun 25, 2008
Messages
2
Reaction score
0
Workaround

Yep, here's a workaround using Items.FindByValue.

In this particular example I'm providing an "other" option on the ddl where the user gets to enter into a textbox if "other" is selected.
For binding, if the value isn't in the ddl, the "other" option is set and a textbox is set and displayed.

Code:
if (ddlDescription.Items.FindByValue(this.FinancialItem.description) != null)
{
    this.ddlDescription.SelectedValue = this.FinancialItem.description;
}
else
{
    this.ddlDescription.SelectedValue = "Weekly Expense: Other";
    this.txtDescription.Text = this.FinancialItem.description;
    this.txtDescription.Visible = true;
}

.net should still have thrown an exception though!
If you actually want to bubble up an exception, you could throw it manually from inside the else block.
 

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,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top