动态绑定下拉控件的选择

时间:2015-03-16 16:12:01

标签: c# asp.net drop-down-menu

我有一个主页,我通过<asp:Repeater.../>控件创建了div。现在,在<div>按钮上的点击事件中,我将页面重定向到注册表单,我有一个<asp:DropDown.../>控件。

在注册页面的Page_Load事件中,我将填充数据库中的下拉列表并设置DataTextFieldDataValueField

现在,我正在将EventTypeID分配给dropdown.DataValueFieldNamedropdown.DataTextField。我还检查了渲染时的下拉列表包含EventTypeID字段中的value ..

以下是代码:

protected void Page_Load(object sender, EventArgs e)
    {
        EventTypeLogic eventTypeLogic = new EventTypeLogic();
        int eventTypeID = Convert.ToInt32(Request.QueryString["Id"]);

        ddlEventType.DataSource = eventTypeLogic.populateEventTypeDDL();
        ddlEventType.DataValueField = "EventTypeID";
        ddlEventType.DataTextField = "Name";
        ddlEventType.DataBind();
        ddlEventType.Items.Insert(0, new ListItem("Select Event Type", "0"));

        if (eventTypeID > 0)
        {
            ddlEventType.SelectedIndex = eventTypeID;
        }
    }

DropDown aspx代码:

<asp:DropDownList ID="ddlEventType" runat="server" CssClass="span2 form-info" />

首页代码:

</p><h6><a class="btn btn-custom" href='<%# "HostEvent.aspx?ID=" + Eval("EventTypeID") %>' ><b>host event</b></a></h6> 

问题:我希望该下拉列表应根据主页上的选择预先选择值。

更新:

protected void Page_Load(object sender, EventArgs e)
    {
        EventTypeLogic eventTypeLogic = new EventTypeLogic();
        int eventTypeID = Convert.ToInt32(Request.QueryString["Id"]);

        string name = eventTypeLogic.resolveToName(eventTypeID);

        ddlEventType.DataSource = eventTypeLogic.populateEventTypeDDL();
        ddlEventType.DataValueField = "EventTypeID";
        ddlEventType.DataTextField = "Name";
        ddlEventType.Items.Insert(0, new ListItem("Select Event Type", "0"));
        //ddlEventType.DataBind();


        ddlEventType.SelectedIndex = eventTypeID;
        ddlEventType.DataBind();

    }

1 个答案:

答案 0 :(得分:0)

如果您希望EventName显示为Ddl中的预选值,而不仅仅使用eventTypeId启动查询,并获取该事件的所有信息并尝试此操作。< / p>

// i suppose when you fire query you get an Object `EventDetails`
if (eventTypeID > 0)
        {
            ddlEventType.SelectedIndex = eventTypeID;
ddlEventType.SelectedValue = EventDetails.EventTypeID.ToString();
        }

这应该有用!