如果在项目列表中找不到选定的值,请不要绑定下拉列表

时间:2017-07-06 07:28:58

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

如果SelectedValue='<%# Bind("AccID") %>'不在项目列表中,如何告诉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>

1 个答案:

答案 0 :(得分:0)

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

但我希望我可以通过SelectedValue='<%# Bind("AccID") %>'来解决它。

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