问题
DropDownList keeps returning this error :(
Here is my aspx code
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DataKeyNames="username" DataSourceID="SqlDataSource1" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">
<EditRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<Fields>
<asp:TemplateField HeaderText="username" SortExpression="username">
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Bind("username") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title" SortExpression="title">
<EditItemTemplate>
<asp:DropDownList ID="detailsUserTitle" runat="server" SelectedValue='<%# Bind("title") %>' DataSourceID="SqlDataSource1">
<asp:ListItem Value="-1">Select Title</asp:ListItem>
<asp:ListItem Value="Mr">Mr</asp:ListItem>
<asp:ListItem Value="Mrs">Mrs</asp:ListItem>
<asp:ListItem Value="Miss">Miss</asp:ListItem>
<asp:ListItem Value="Ms">Ms</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorTitle"
ControlToValidate="detailsUserTitle" runat="server" ErrorMessage="Title is a required field"
Text="*" ForeColor="Red" InitialValue="-1"></asp:RequiredFieldValidator>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("title") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("title") %>'></asp:Label>
</ItemTemplate>
I have been looking online for advice, but there hasn't been a conclusive one that helped me. Please help. I didn't add any code behind related to this issue.
Thank you
回答1:
Your issue is with the DDL attribute SelectedValue='<%# Bind("title") %>'
Your SQL DataSource "SqlDataSource1" may not be returning any of the values from Mr, Mrs, Miss or MS.
If Title field has a different value you get this error
UPDATE
You may validate your Title string as below before binding. But, I wouldn't recommend this. I prefer if you could validate the values before retrieving from your data source. The ideal solution would be to bind the DropDownList with same set of values before finding the values in it. then you won't miss anything.
Here's the quick fix. :-)
SelectedValue='<%# (!string.IsNullOrEmpty(Bind("title")) || "Mr, Mrs, Miss, MS".IndexOf(Bind("title")) > -1) ? Bind("title") : "-1" %>'
UPDATE 2 Here you go :-D
SelectedValue='<%# (!string.IsNullOrEmpty((string)Eval("title")) || "Mr, Mrs, Miss, MS".IndexOf((string)Eval("title")) > -1) ? (string)Eval("title") : "-1" %>'
Please accept the answer if it resolves your issue. All the best!
来源:https://stackoverflow.com/questions/25718960/detailsusertitle-has-a-selectedvalue-which-is-invalid-because-it-does-not-exis