ASP.NET Web Form ListView进入编辑模式时下拉列表报错问题
ASP.NET ListView编辑模式下拉列表SelectedValue无效问题
我使用ListView控件展示SQL表数据,同时有一个录入表单,表单中的下拉列表(ID: DDL_code)从另一张包含Code和CodeName列的表填充,填充代码如下:
DDL_code.DataTextField = "CodeName"; DDL_code.DataValueField = "Code"; DDL_code.DataBind();
我的ItemDataBound方法代码如下:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e) { // 检查项是否处于编辑模式 if (e.Item.ItemType == ListViewItemType.DataItem && ListView1.EditIndex == e.Item.DataItemIndex) { // 查找编辑模式下的TextBox控件 TextBox txtStoreNum = (TextBox)e.Item.FindControl("txtEditStoreNum"); TextBox txtStoreName = (TextBox)e.Item.FindControl("txtEditStoreName"); TextBox txtStoreContact = (TextBox)e.Item.FindControl("txtEditStoreContact"); DropDownList DDL_code = (DropDownList)e.Item.FindControl("EditDDL_Code"); TextBox txtIssue = (TextBox)e.Item.FindControl("txtEditIssue"); // 用当前值填充TextBox控件 if (txtStoreNum != null) txtStoreNum.Text = ((DataRowView)e.Item.DataItem)["StoreNum"].ToString(); if (txtStoreName != null) txtStoreName.Text = ((DataRowView)e.Item.DataItem)["StoreName"].ToString(); if (txtStoreContact != null) txtStoreContact.Text = ((DataRowView)e.Item.DataItem)["StoreContact"].ToString(); if (DDL_Code != null) DDL_Code.SelectedValue = ((DataRowView)e.Item.DataItem)["Code"].ToString(); if (txtIssue != null) txtIssue.Text = ((DataRowView)e.Item.DataItem)["Issue"].ToString(); } }
EditDDL_Code和DDL_Code的标记代码如下:
<td> <asp:DropDownList ID="EditDDL_Code" runat="server" Text='<%# Bind("Code") %>'></asp:DropDownList> </td>
<asp:DropDownList ID="DDL_Code" runat="server" placeholder="Trouble Code" TabIndex="4" ToolTip="Choose trouble code" /><br /><br />
点击编辑按钮时出现错误:
'EditDDL_Code' System.ArgumentOutOfRangeException: 'EditDDL_code' 的SelectedValue无效,因为它不在项列表中。参数名: value
相关的其他方法代码如下:
protected void ListView1_ItemEditing(object sender, ListViewEditEventArgs e) { Debug.WriteLine("ListView1_ItemEditing"); ListView1.EditIndex = e.NewEditIndex; BindListViewData(); } protected void BindListViewData() { Debug.WriteLine("BindListViewData"); // 获取登录用户名 string loggedInUsername = _Default.uName; // 查询当前用户当日数据的SQL语句 string query = "SELECT Id, StoreNum, StoreName, StoreContact, CallDate, CallTime, Code, Issue, UserN " + "FROM call_log " + "WHERE UserN = @LoggedInUsername AND CONVERT(date, CallDate) = CONVERT(date, GETDATE())"; // 从数据库获取数据 DataTable dt = ExecuteQuery(query, loggedInUsername); // 将数据绑定到ListView控件 ListView1.DataSource = dt; ListView1.DataBind(); } private DataTable ExecuteQuery(string query, string loggedInUsername) { // 存储结果的DataTable DataTable dt = new DataTable(); // Using语句确保资源正确释放 using (SqlConnection conn = new SqlConnection(cs)) { // 创建带参数的SqlCommand using (SqlCommand cmd = new SqlCommand(query, conn)) { // 添加参数 cmd.Parameters.AddWithValue("@LoggedInUsername", loggedInUsername); // 打开连接并填充DataTable conn.Open(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); } } // 返回填充后的DataTable return dt; }
内容的提问来源于stack exchange,提问作者Reaven Smith
相关产品推荐
相关产品推荐

