Reputation: 1859
I have two dorpdownlists in my page. One is databound, and another has values added at the design time.
<asp:DropDownList ID="maritalStatus" runat="server" Width="180px">
<asp:ListItem Value="-1">--SELECT--</asp:ListItem>
<asp:ListItem>Single</asp:ListItem>
<asp:ListItem>Divorced</asp:ListItem>
<asp:ListItem>Married</asp:ListItem>
<asp:ListItem>Widow(er)</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="country" runat="server" Width="180px">
</asp:DropDownList>
This is my Codebehind for filling the country dropDownList
using (SqlCommand com = new SqlCommand("SELECT CountryID, CountryName FROM Country", con))
{
SqlDataAdapter dad = new SqlDataAdapter(com);
DataTable countryTab = new DataTable("Country");
dad.Fill(countryTab);
country.DataSource = countryTab;
country.DataTextField = "CountryName";
country.DataValueField = "CountryID";
country.DataBind();
country.Items.Insert(0, new ListItem("--SELECT--", "-1"));
}
But when I set "--SELECT--" to both dropDownLists, the maritalStatus dropDownList works fine; But, country dropdown shows this error
"'country' has a SelectedValue which is invalid because it does not exist in the list of items"
maritalStatus.Text = "--SELECT--";
country.Text = "--SELECT--";
If I set country Text as "-1", It will work fine. I don't understand why both dropDownLists are behaving in different way.
Upvotes: 1
Views: 546
Reputation: 1943
Just replace
country.Items.Insert(0, new ListItem("--SELECT--", "-1"));
To
country.Items.Insert(0, new ListItem("--SELECT--", "0"));
Upvotes: 0
Reputation: 21795
Your problem is there is no Value like --SELECT--
in your dropdown therefore their is no match in the ListItem
collection and hence the exception.
According to documentation of Dropdownlist Text property it:-
Gets or sets the SelectedValue property of the ListControl control.
Thus, when you are saying country.Text = "--SELECT--";
, it is searching for a value of --SELECT--
which is not present in the collection but when you search for -1
it finds it and there is no exception.
Coming to the behavior difference in two dropdowns, it doesn't matter whether you bind it programmatically
or declaratively
both will behave the same and you will get the exception in both case.
Upvotes: 3
Reputation: 71
Just Replace
country.Items.Insert(0, new ListItem("--SELECT--", "-1"));
to
country.Items.Insert("0","--SELECT--");
this will solve issue
Upvotes: 1