【问题标题】:Do not bind drop down list if selected value not found in list of items如果在项目列表中未找到所选值,则不绑定下拉列表
【发布时间】:2026-01-23 02:25:02
【问题描述】:

如果AccID 不在项目列表中,我如何告诉SelectedValue='<%# Bind("AccID") %>' 不执行绑定?

<EditItemTemplate>
    <asp:ObjectDataSource ID="ObjectDataSourceAccount" runat="server" SelectMethod="GetUsableAccountByUser"
    TypeName="t_MT_AccCode" OnSelected="ObjectDataSourceAccount_Selected" OnSelecting="ObjectDataSourceAccount_Selecting">
        <SelectParameters>
            <asp:Parameter Name="companyCode" />
            <asp:Parameter Name="departmentCode" />
            <asp:Parameter Name="badgeNumber" />
            <asp:Parameter Name="userRole" />
        </SelectParameters>
    </asp:ObjectDataSource>
    <asp:DropDownList ID="DropDownListAccount" runat="server" DataSourceID="ObjectDataSourceAccount"
    DataTextField="accountDesc" DataValueField="id" 
    SelectedValue='<%# Bind("AccID") %>' 
    ondatabinding="DropDownListAccount_DataBinding" 
    ondatabound="DropDownListAccount_DataBound">
    </asp:DropDownList>
</EditItemTemplate>

【问题讨论】:

  • 这会做到Bind("AccID") != null ? Bind("AccID") : "[Add Default Value]" 例如“0”
  • @Prabhat AccID 不必为 null,它可以是 123 但项目列表只有 ABCDEF。在这种情况下会导致错误。
  • Null 用于在项目列表中不存在“AccID”时处理“对象引用”错误。
  • @Prabhat 但我的错误是'DropDownListAccount' has a SelectedValue which is invalid because it does not exist in the list of items
  • 非常感谢您的澄清。如果是这种情况,那么您可以使用 Gridview Rowdatabound 事件来查找 DropDownList 并搜索 AccId 是否存在于项目列表中。如果是,则分配相同的值,否则分配默认值。

标签: c# asp.net data-binding webforms dropdown


【解决方案1】:

这就是我解决这个问题的方法。

但我希望我可以通过SelectedValue='&lt;%# Bind("AccID") %&gt;' 来解决它。

protected void DropDownListAccount_DataBound(object sender, EventArgs e)
{
    DropDownList dropDownListAccount = (DropDownList)sender;
    DataRowView currentDataRowView = (DataRowView)((GridViewRow)dropDownListAccount.Parent.Parent).DataItem;
    int currentRowDataKeyItemId = int.Parse(currentDataRowView["ID"].ToString());
    int accountId = t_MT_MTItem.GetAccountIdByItemId(currentRowDataKeyItemId);
    dropDownListAccount.SelectedValue = accountId.ToString();
}

【讨论】:

    最近更新 更多