在下拉列表填充数据之前,ObjectDataSource正在选择

时间:2018-04-05 08:29:31

标签: c# webforms .net-4.0 dropdown objectdatasource

我在第一个Page_Load:

期间绑定了我的DropDownList
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Function.LoopChangeControlMtText(this.Controls);

        BindProcessingDepartment();
        BindDropDownListYear();
        if (DropDownListProcessingDepartment.Items.Count > 0)
        {
            if (DropDownListYear.Items.Count > 0)
            {
                BindGridViewUploadedItemNoCommitment();
            }
        }
    }
}

private void BindDropDownListYear()
{
    MTConfig mtConfig = new MTConfig();
    DataTable mtCreatedYear = new DataTable();
    mtCreatedYear = mtConfig.getMtCreatedYear();
    if (mtCreatedYear == null)
    {
        Page.ClientScript.RegisterStartupScript(Page.GetType(), "alertFailProcessDeptBind", "alert('Failed to get " + ConfigurationManager.AppSettings["systemNameShortFormWithoutE"].Trim() + " created year.\\nPlease contact MIS.\\nContact info. at the bottom of the page.');", true);
    }
    else
    {
        DropDownListYear.DataSource = mtCreatedYear;
        DropDownListYear.DataMember = "MtCreatedYear";
        DropDownListYear.DataValueField = "MtCreatedYear";
        DropDownListYear.SelectedIndex = 0;
        DropDownListYear.DataBind();
    }
}

但我的对象数据源在下拉列表填充数据之前执行选择。第一次选择时,下面的SelectedValue为空。

protected void objectDataSourceUploadedItemWithoutCommitment_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
    try
    {
        e.InputParameters["CreatedYear"] = Convert.ToInt32(DropDownListYear.SelectedValue.ToString());
    }
    catch (Exception ex)
    {
        LogHandler.LogError(logger, ex);
        Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "Error occurred during objectDataSourceUploadedItemWithoutCommitment_Selecting!", true);
    }
}

是否可以更改objectDataSourceUploadedItemWithoutCommitment_SelectingPage_Load的订单?

除了DropDownListYear.Items.Insert(0, new ListItem("Please select year", "0"))强迫用户选择一年之外,我还能如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以使用AppendDataBoundItems="True"属性

在正面完成此操作
<asp:DropDownList ID="DropDownListYear" AppendDataBoundItems="True" runat="server" >
    <asp:ListItem>Please select year</asp:ListItem>
</asp:DropDownList>

这将自动附加第一个项目,其中包含从DataSource填充的所有其他项目。