Reputation: 1453
I am getting the below error when I try to bind data.
SelectedValue which is invalid because it does not exist in the list of items
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="JobCategoryEntityDataSource" DataTextField="ItemValue"
DataValueField="ItemValue" SelectedValue='<%# Bind("JobCategory") %>'
Width="230px">
</asp:DropDownList>
I know the reason why I am getting this error. It is because it cant find the value in the selection. When JohCategory field from the transaction table can not find it in the list that is coming from JobCategoryEntityDataSource, it simply throws an error.
All I want to do is not bind the data if it can't find it in the dropdownlist and don't want to throw errors. How can I do this ?
Another option is if it can't find the matching value, just add "Please select" or something similar.
Can someone help please ?
Upvotes: 0
Views: 5075
Reputation: 5818
You can select the value in DataBound
event of the dropdown
. You can check for the existence of value and then select it or you can implement try catch
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="JobCategoryEntityDataSource" DataTextField="ItemValue"
DataValueField="ItemValue"
Width="230px" OnDataBound="DropDownList2_DataBound">
</asp:DropDownList>
<asp:HiddenField ID="JobCategory" runat="server" value='<%# Bind("JobCategory") %>'></asp:HiddenField>
Code-Behind
protected void DropDownList2_DataBound(object sender, EventArgs e)
{
try{
HiddenField hf = (HiddenField)Form.FindControl("JobCategory");
DropDownList2.SelectedValue = hf.Value;
}Catch(Exception ex){
}
}
Upvotes: 1
Reputation: 10254
You need to bind it in the code behind and either
FindByName
first, then, optionally, add it if not.Upvotes: 0