C# DropDownList 有一个无效的 SelectedValue,因为它不存在于项目列表中。参数名称:值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19770207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DropDownList has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value
提问by New2This
I keep getting the above error in the title line and it makes no sense, because I am using a sample table with only 5 records and each record has a value as per the drop down menu.
我一直在标题行中收到上述错误,这是没有意义的,因为我使用的示例表只有 5 条记录,并且每条记录都有一个下拉菜单中的值。
This is my code used to declare the drop down list. I have joined two tables in my SQL data source to reflect what I want populated in the grid view and have hidden columns as necessary. I am using the same data source to populate the drop down list any help would be most appreciated
这是我用于声明下拉列表的代码。我在我的 SQL 数据源中加入了两个表,以反映我想要在网格视图中填充的内容,并根据需要隐藏列。我使用相同的数据源来填充下拉列表任何帮助将不胜感激
<asp:DropDownList ID="DropDownListCurrency" runat="server"
CausesValidation="True" DataSourceID="GridView"
DataTextField="Currency" DataValueField="Currency_ID"
AppendDataBoundItems="True">
<asp:ListItem Value="0" Text="<Select>" Enabled="True"></asp:ListItem>
</asp:DropDownList>
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GridViewRow row = GridView1.SelectedRow;
AccountNumber.Text = (string)row.Cells[0].Text;
....
DropDownListCurrency.SelectedValue = (string)row.Cells[8].Text;
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}
采纳答案by Karl Anderson
Attempt to find the value in the drop down list before attempting to set the SelectedValue, like this:
在尝试设置 SelectedValue 之前尝试在下拉列表中查找值,如下所示:
if (DropDownListCurrency.Items.FindByValue(row.Cells[8].Text.ToString().Trim()) != null)
{
DropDownListCurrency.SelectedValue = row.Cells[8].Text.ToString().Trim();
}
Note: The Trim()
call will remove any leading or trailing spaces in your text box text, which could be a cause for a match not being found.
注意:该Trim()
调用将删除文本框文本中的任何前导或尾随空格,这可能是找不到匹配项的原因。
So your full code should be this:
所以你的完整代码应该是这样的:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GridViewRow row = GridView1.SelectedRow;
AccountNumber.Text = (string)row.Cells[0].Text;
....
if (DropDownListCurrency.Items.FindByValue(row.Cells[8].Text.ToString().Trim()) != null)
{
DropDownListCurrency.SelectedValue = row.Cells[8].Text.ToString().Trim();
}
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}
回答by Ryuzaki
Hi maybe in that cell from your gridview have white space or dropdownlist have white space for example isn't the same this
嗨,也许在您的 gridview 中的那个单元格中有空格或下拉列表中有空格,例如这不一样
Dolar__ = Dolar
美元__ = 美元
or
或者
Dolar = Dolar__
美元 = 美元__
use a Trim in code behind to clear white spaces in SQL Server don't use Rtrim this isn't good practices
在代码中使用 Trim 来清除 SQL Server 中的空格不要使用 Rtrim 这不是好的做法
回答by FabioA
Dropdownlist values ??are different from the values ??in the column of the database.
下拉列表的值与数据库列中的值不同。
Example: The dropdown show Emma, but in the database exist Emma and Emma1.
示例:下拉列表显示 Emma,但数据库中存在 Emma 和 Emma1。
The dropdownlist cannot find the value Emma1.
下拉列表找不到值 Emma1。
回答by Philip Johnson
This can happen if the rows in the drop down list are in a related table and referential integrity is not being used in the database. In my case, I use referential integrity but I add a boolean to the drop down list record to say "Disabled" - i.e. I no longer want users to be able to select this value in the drop down list. So I filter the drop down list to show only values that are not "Disabled", but then the problem then is that existing data might already contain the value, leading to the error message above when Edit is pressed on the grid.
如果下拉列表中的行在相关表中并且数据库中未使用参照完整性,则可能会发生这种情况。在我的例子中,我使用参照完整性,但我在下拉列表记录中添加了一个布尔值来表示“已禁用”——即我不再希望用户能够在下拉列表中选择这个值。因此,我过滤下拉列表以仅显示未“禁用”的值,但问题是现有数据可能已经包含该值,导致在网格上按下 Edit 时出现上述错误消息。
The way I handle this situation, is as follows:
我处理这种情况的方式如下:
- Make the drop down list in question unbound to avoid the error.
Add the following code in the code behind:
protected void StaffTypeGridView_OnRowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType != DataControlRowType.DataRow || e.Row.RowIndex != StaffTypeGridView.EditIndex) return; var staffType = (StaffType)e.Row.DataItem; var appCode = staffType.AppCode; var ddl = (DropDownList) e.Row.FindControl(ddlName); if (!string.IsNullOrEmpty(value) && ddl.Items.FindByValue(value) == null) { ddl.Items.Add(new ListItem { Value = value, Text = value + " (Deleted)" }); } ddl.SelectedValue = value; }
Don't forget to write code either in the DropDownList_OnSelectedIndexChanged or GridViewOnRowUpdating to update the value back into the data source (as its an unbound field).
Add a custom validator to the EditItemTemplate to ensure that data that has been deleted cannot be entered, i.e. the user MUST change the value in the drop down list in order to save.
- 取消绑定有问题的下拉列表以避免错误。
在后面的代码中添加如下代码:
protected void StaffTypeGridView_OnRowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType != DataControlRowType.DataRow || e.Row.RowIndex != StaffTypeGridView.EditIndex) return; var staffType = (StaffType)e.Row.DataItem; var appCode = staffType.AppCode; var ddl = (DropDownList) e.Row.FindControl(ddlName); if (!string.IsNullOrEmpty(value) && ddl.Items.FindByValue(value) == null) { ddl.Items.Add(new ListItem { Value = value, Text = value + " (Deleted)" }); } ddl.SelectedValue = value; }
不要忘记在 DropDownList_OnSelectedIndexChanged 或 GridViewOnRowUpdating 中编写代码以将值更新回数据源(作为其未绑定字段)。
在 EditItemTemplate 中添加自定义验证器,以确保已删除的数据无法输入,即用户必须更改下拉列表中的值才能保存。
This sounds quite complicated to explain but is quite a straightforward way of providing this functionality, unless anybody has any better ideas...
这听起来解释起来很复杂,但这是提供此功能的一种非常直接的方式,除非有人有更好的想法......
回答by Veeramuthu
You can use the Trim() method
您可以使用 Trim() 方法
ddlname.Text = dt.Rows[0][3].ToString().Trim();
回答by coder
it's so simple just use this
就这么简单就用这个
Dropdown.SelectedValue = null;
Dropdown.DataBind();
回答by Michal ?uvada
Setting Text
property of DropDownList
in ASPX to value missing from ItemList
causes the same error.
将ASPX 中的Text
属性设置DropDownList
为缺失值ItemList
会导致相同的错误。
In my case what happened was that I have added by mistake meta-resourcekey
tag where Text
property was set to value missing in ItemList
.
就我而言,发生的情况是我错误地添加了meta-resourcekey
标签,其中Text
属性设置为ItemList
.
The resources values were:
资源值为:
table {
border-collapse: collapse;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
table th, table td {
border: solid 1px darkgray;
padding: 0 5px;
}
table.tr:first(){
}
<table css="table">
<tr>
<th>Name</th>
<th>Value</th>
<th>Comment</th>
</tr>
<tr>
<td>Template.Text</td>
<td>Template</td>
<td></td>
</tr>
<tr>
<td>Template.ToolTip</td>
<td>template of standard outgoing email settings</td>
<td></td>
</tr>
</table>
and ASPX control was:
和 ASPX 控件是:
<asp:DropDownList runat="server" ID="ddlTemplate" CssClass="form-control dropdownlist" meta:resourcekey="Template" >
<asp:ListItem Selected="True" meta:resourcekey="TemplateEmpty" Value="EMPTY" />
<asp:ListItem Selected="False" meta:resourcekey="TemplatePOP3" Value="POP3" />
<asp:ListItem Selected="False" meta:resourcekey="TemplatePOP3Secured" Value="POP3S" />
<asp:ListItem Selected="False" meta:resourcekey="TemplateIMAP" Value="IMAP" />
<asp:ListItem Selected="False" meta:resourcekey="TemplateIMAPSecured" Value="IMAPS" />
</asp:DropDownList>
Removing the meta:resourcekey
did the trick for me.
删除meta:resourcekey
对我来说很有效。
回答by JIYAUL MUSTAPHA
#region by zia for if item not exist in dropdownlist
string qlf = dsEmp.Tables["tblEmp"].Rows[0]["Group"].ToString();
ListItem selLqli = ddlGroup.Items.FindByText(qlf.Trim());
if (selLqli != null)
{
ddlGroup.ClearSelection();
}
else
{
ddlGroup.SelectedIndex = 0;
}
#endregion