ASP.net Web 表单项目,在 ListView 上进入编辑模式时出现问题

问题描述 投票:0回答:1

我有一个 listView,它显示来自 SQL 表的数据,到目前为止效果很好,我还有一个在其中输入数据的表单,在该表单中,有一个从另一个表填充的下拉列表(ID:DDL_code)。为了详细说明,提供下拉列表的表有 2 列 Code 和 CodeName,填充下拉列表的方法使用:

DDL_code.DataTextField = "CodeName";
DDL_code.DataValueField = "Code";
DDL_code.DataBind(); 

我的itemdatabound方法是:

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    // Check if the item is in edit mode
    if (e.Item.ItemType == ListViewItemType.DataItem && ListView1.EditIndex == e.Item.DataItemIndex)
    {
        // Find the TextBox controls in edit mode
        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");

        // Populate TextBox controls with the current values
        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();
    }
}

DDL_Code 和 EditDDL_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,因为它不存在于项目列表中。 参数名称:值'

c# asp.net webforms
1个回答
0
投票

如果 [code] 为 null,那么它就不会出现在该列表中,不是吗?

所以,你需要:

        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");

        DataRowView gRow = (DataRowView)e.Item.DataItem);

        txtStoreNum.Text = gRow["StoreNum"].ToString();
        txtStoreName.Text = gRow["StoreName"].ToString();
        txtStoreContact.Text = gRow["StoreContact"].ToString();
        if (gRow["Code"] != null)
            DDL_Code.SelectedValue = gRow["Code"].ToString();
        
        txtIssue.Text = gRow["Issue"].ToString();
© www.soinside.com 2019 - 2024. All rights reserved.