【问题标题】:DropDownList error 'does not exist in the in the list of items' ASP.NET C#DropDownList 错误“项目列表中不存在”ASP.NET C#
【发布时间】:2011-06-04 09:13:53
【问题描述】:

我正在尝试制作自定义申请表。到目前为止,我已经添加了一些控件,例如 TextBox 和 Button,直到我使用 DropDownList 控件修改了一些 TextBox。当我单击添加按钮时,它返回一个错误:

'categoryDropDownList' 有一个无效的 SelectedValue,因为它不存在于项目列表中。 参数名称:值

我在后面附上了我的代码示例代码:

public partial class Test2 : System.Web.UI.Page
    {
        public string GetConnectionString()
        {
            return System.Configuration.ConfigurationManager.ConnectionStrings["LibrarySystemConnectionString"].ConnectionString;
        }

        private void execution(string bookid, string booktitle, string lastname, string firstname, string description, string categoryid, string dateadded, string quantity, string statusid)
        {
            SqlConnection conn = new SqlConnection(GetConnectionString());

            string sql = "INSERT INTO TblBooks(bookid, booktitle, lastname, firstname, description, categoryid, dateadded, quantity, statusid) VALUES "+" (@bookid, @booktitle,@lastname, @firstname, @description, @categoryid, @dateadded, @quantity, @statusid)";

            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlParameter[] pram = new SqlParameter[9];
                pram[0] = new SqlParameter("@bookid", SqlDbType.BigInt, 64);
                pram[1] = new SqlParameter("@booktitle", SqlDbType.NVarChar, 50);
                pram[2] = new SqlParameter("@lastname", SqlDbType.NVarChar, 50);
                pram[3] = new SqlParameter("@firstname", SqlDbType.NVarChar, 50);
                pram[4] = new SqlParameter("@description", SqlDbType.NVarChar, 200);
                pram[5] = new SqlParameter("@categoryid", SqlDbType.Int, 32);
                pram[6] = new SqlParameter("@quantity", SqlDbType.Int, 32);
                pram[7] = new SqlParameter("@statusid", SqlDbType.Int, 32);
                pram[8] = new SqlParameter("@dateadded", SqlDbType.DateTime, 32);

                pram[0].Value = bookid;
                pram[1].Value = booktitle;
                pram[2].Value = lastname;
                pram[3].Value = firstname;
                pram[4].Value = description;
                pram[5].Value = categoryid;
                pram[6].Value = quantity;
                pram[7].Value = statusid;
                pram[8].Value = dateadded;

                for (int i = 0; i < pram.Length; i++)
                {
                    cmd.Parameters.Add(pram[i]);
                }
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
            }
            catch (System.Data.SqlClient.SqlException ex_msg)
            {

                string msg = "Error occured while inserting";
                msg += ex_msg.Message;
                throw new Exception(msg);
            }

            finally
            {
                conn.Close();
            }
            }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (bookidTextBox.Text == "")
            {
                Response.Write("Please complete the form");
            }

            else
            {
             execution(bookidTextBox.Text, booktitleTextBox.Text, lastnameTextBox.Text, firstnameTextBox.Text, descriptionTextBox.Text, categoryDropDownList.SelectedValue, dateaddedTextBox.Text, quantityTextBox.Text, statusDropDownList.SelectedValue);
                //conform.Visible = true;
                bookidTextBox.Text = "";
                booktitleTextBox.Text = "";
                lastnameTextBox.Text = "";
                firstnameTextBox.Text = "";
                descriptionTextBox.Text = "";
                categoryDropDownList.SelectedValue = "";
                dateaddedTextBox.Text = "";
                statusDropDownList.SelectedValue = "";
                quantityTextBox.Text = "";

            }
        }
    }
}

这是表单的示例代码:

<table class="style1">
    <tr>
        <td class="style2">
            ISBN:
            </td>
            <td class="style3">
            <asp:TextBox ID="bookidTextBox" runat="server" Text='<%# Bind("bookid") %>'>
            </asp:TextBox>
            </td>
            <td>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator" runat="server" ControlToValidate="bookidTextBox" ErrorMessage="* " ValidationGroup="addbooks">
            </asp:RequiredFieldValidator>
        </td>
    </tr>

<tr>
<td class="style2">
Title:
</td>
<td class="style3">
<asp:TextBox ID="booktitleTextBox" runat="server" Text='<%# Bind("booktitle") %>'>
</asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="booktitleTextBox" ErrorMessage="* " ValidationGroup="addbooks">
</asp:RequiredFieldValidator>
</td>
</tr>

... (cut some code here)

<tr>
<td class="style2">
Category:
</td>
<td class="style3">
    <asp:DropDownList ID="categoryDropDownList" runat="server" 
        DataSourceID="categoryDataSource" DataTextField="name"
        DataValueField="categoryid" >
    </asp:DropDownList>
    <asp:SqlDataSource ID="categoryDataSource" runat="server"
        ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>" 
        SelectCommand="SELECT [categoryid], [name] FROM [TblCategory]">
    </asp:SqlDataSource>
</td>
</tr>

...

<tr>
<td class="style2">
Status:</td>
<td class="style3">
    <asp:DropDownList ID="statusDropDownList" runat="server" 
        DataSourceID="statusDataSource" DataTextField="statusname" 
        DataValueField="statusid" >
    </asp:DropDownList>
    <asp:SqlDataSource ID="statusDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>" 
        SelectCommand="SELECT [statusid], [statusname] FROM [BookStatus]">
    </asp:SqlDataSource>
</td>
</tr>

</table>
</div>

<asp:Button ID="AddBtn" runat="server" Text="Add" OnClick="Button1_Click" Width="100px" />
<br />
<br />

<b>Book List</b>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    DataKeyNames="bookid" DataSourceID="bookDataSource">
    <Columns>
        <asp:BoundField DataField="bookid" HeaderText="bookid" ReadOnly="True" 
            SortExpression="bookid" />
        <asp:BoundField DataField="booktitle" HeaderText="booktitle" 
            SortExpression="booktitle" />
        <asp:BoundField DataField="lastname" HeaderText="lastname" 
            SortExpression="lastname" />
        <asp:BoundField DataField="firstname" HeaderText="firstname" 
            SortExpression="firstname" />
        <asp:BoundField DataField="categoryid" HeaderText="categoryid" 
            SortExpression="categoryid" />
        <asp:BoundField DataField="description" HeaderText="description" 
            SortExpression="description" />
        <asp:BoundField DataField="dateadded" HeaderText="dateadded" 
            SortExpression="dateadded" />
        <asp:BoundField DataField="statusid" HeaderText="statusid" 
            SortExpression="statusid" />
        <asp:BoundField DataField="quantity" HeaderText="quantity" 
            SortExpression="quantity" />
        <asp:CheckBoxField DataField="isdeleted" HeaderText="isdeleted" 
            SortExpression="isdeleted" />
    </Columns>
</asp:GridView>

当我尝试将 DropDownList 转换为文本框时它起作用了,但是如何将它与 DropDownList 控件绑定??

我们将不胜感激!提前致谢。

【问题讨论】:

  • 请不要张贴代码墙。将您的问题简化为本质,即表现出行为的最小可能的 sn-p。你会更快得到答案,而且这些答案会更好。
  • 该错误表明您正在尝试将下拉列表的 SelectedValue 设置为您放入下拉列表中的项目中不存在的值。在将某些内容设为选定值之前,您必须首先确保它在 .Items 集合中。
  • 这与将所选值设置为“”有关。我猜您的数据源在“”记录集中没有任何数据。

标签: c# asp.net


【解决方案1】:

您的DropDown 绑定到SqlDataSource。当你执行categoryDropDownList.SelectedValue = ""时,DropDown在数据源中寻找空值,但是找不到,所以失败了。

如果这是您想要实现的目标,可能想要运行 dropDownList.ClearSelection()

这里是演示问题的简化代码示例

protected void Page_Load(object sender, EventArgs e)
{
    var items = new[] { new { Id = 1, Name = "Test1" }, new { Id = 2, Name = "Test2" } };

    dropDownList.DataSource = items;
    dropDownList.DataValueField = "Id";
    dropDownList.DataTextField = "Name";
    dropDownList.DataBind();
}

protected void Button1_Click(object sender, EventArgs e)
{
    dropDownList.SelectedValue = ""; // trhows exception
    dropDownList.ClearSelection(); // works
}

【讨论】:

  • 使用 IsPostBack 页面属性确保每次页面请求都发生一次 DataBinding。
【解决方案2】:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-18
  • 2014-01-26
  • 2020-07-18
相关资源
最近更新 更多