在页面上找到Usercontrol的Dropdownlist选择值

时间:2011-04-20 20:15:13

标签: c# asp.net

我有一个名为 UCCountry.ascx 的用户控件,此用户控件只有一个国家/地区的下拉列表。我的页面名称是 MyFirstPage.aspx ,在此页面上我有一个基于 CountryId 绑定数据的转发器,即 MyfirstPage.aspx 包含Usercontrol。 现在,我想知道当用户使用Usercontrol中的下拉列表更改国家/地区时,如何绑定数据。

注意:我可以使用哪个页面生命周期事件来获取下拉列表的值以及绑定转发器所需的事件。

5 个答案:

答案 0 :(得分:2)

您需要在控件中将DropDownList公开为public。这样,您的页面就可以监听事件并对其进行响应。例如:

UCCountry.ascx

<asp:DropDownList Id="CountryDropDown" ... />

UCCountry.ascx.cs

public DropDownList CountryDropDown { get; protected set; }

MyFirstPage.aspx

<ctl:UCCountry Id="CountryControl" ... />

MyFirstPage.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    this.CountryControl.CountryDropDown.SelectedIndexChanged += new EventHandler(CountryDropDown_SelectedIndexChanged);
}

protected void CountryList_SelectedIndexChanged(object sender, EventArgs e)
{
    // do your databinding here
}

答案 1 :(得分:2)

我找到了解决方案: 我创建了两个成员变量:

/// <summary>
/// The name of the country selection dropdown list in the common header.
/// </summary>
public const string CountryDropDownName = "ucControl1$ddlCountry";

/// <summary>
/// The name of the PostBack event target field in a posted form.  You can use this to  see which
/// control triggered a PostBack:  Request.Form[PostBackEventTarget] .
/// </summary>
public const string PostBackEventTarget = "__EVENTTARGET";

现在覆盖aspx页面上的InitializeCulture。

/// <SUMMARY>
/// Overriding the InitializeCulture method to set the user selected
/// option in the current thread. Note that this method is called much
/// earlier in the Page lifecycle and we don't have access to any controls
/// in this stage, so have to use Form collection.
/// </SUMMARY>
protected override void InitializeCulture()
{
    ///<remarks><REMARKS>
    ///Check if PostBack occured. Cannot use IsPostBack in this method
    ///as this property is not set yet.
    ///</remarks>
    if (Request[PostBackEventTarget] != null)
    {
        string controlID = Request[PostBackEventTarget];

        if (controlID.Equals(CountryDropDownName))
        {
            string selectedValue =
                   Request.Form[Request[PostBackEventTarget]];

           **//Bind your control here based on the countryID.**
        }
    }
    base.InitializeCulture();
}

答案 2 :(得分:1)

我认为即使DropDownList也只需要OnSelectedIndexChanged

protected void countriesDropDownList_OnSelectedIndexChanged(object sender, EventArgs e)
{
    uCCountry.CountryId = countriesDropDownList.SelectedValue;
    uCCountry.DataBind(); // if necessary. 
}
祝你好运!

答案 3 :(得分:1)

您只需将事件从用户控件冒泡到父页面即可。 Here is a question regarding this topican article that explains how to do it

基本思想是,在用户控件中选定的索引更改事件处理程序中,您将触发父页面所订阅的事件。在页面中的事件处理程序中,您可以重新绑定转发器。

答案 4 :(得分:-1)

您想要使用DDL的OnSelectedIndexChanged事件。当事件触发时,您将能够获得所选值。您还需要确保DDL上的AutoPostBack="True"。从那里你可以在事件处理程序中调用数据绑定。