DropDownList有一个SelectedValue,它是无效的,因为它在项列表中不存在.参数名称:value

New*_*his 8 c# sql asp.net visual-studio-2010

我一直在标题行中得到上述错误,这没有任何意义,因为我使用的样本表只有5条记录,每条记录都有一个根据下拉菜单的值.

这是我用来声明下拉列表的代码.我在SQL数据源中加入了两个表来反映我想要在网格视图中填充的内容,并根据需要隐藏列.我使用相同的数据源来填充下拉列表,任何帮助将是最受欢迎的

<asp:DropDownList ID="DropDownListCurrency" runat="server" 
                  CausesValidation="True" DataSourceID="GridView" 
                  DataTextField="Currency" DataValueField="Currency_ID" 
                  AppendDataBoundItems="True"> 

          <asp:ListItem Value="0" Text="&lt;Select&gt;" Enabled="True"></asp:ListItem>
</asp:DropDownList>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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);
    }        
}
Run Code Online (Sandbox Code Playgroud)

Kar*_*son 12

在尝试设置SelectedValue之前尝试在下拉列表中查找值,如下所示:

if (DropDownListCurrency.Items.FindByValue(row.Cells[8].Text.ToString().Trim()) != null)
{
    DropDownListCurrency.SelectedValue = row.Cells[8].Text.ToString().Trim();
}
Run Code Online (Sandbox Code Playgroud)

注意:该Trim()调用将删除文本框文本中的任何前导或尾随空格,这可能导致找不到匹配项.

所以你的完整代码应该是这样的:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

就这么简单就用这个

Dropdown.SelectedValue = null;
Dropdown.DataBind();
Run Code Online (Sandbox Code Playgroud)

  • 他们把那个放在哪里?为什么这有效而其原始版本无效?添加更多答案以使其真正有用。 (2认同)