简体   繁体   中英

Do not bind drop down list if selected value not found in list of items

How do I tell SelectedValue='<%# Bind("AccID") %>' do not perform the binding if AccID is not in the list of items?

<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>

This is how I solved this issue.

But I was hoping I can solve it through SelectedValue='<%# Bind("AccID") %>' instead.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM