繁体   English   中英

在页面上找到Usercontrol的下拉列表选定的值

[英]Find Usercontrol's Dropdownlist selected value on Page

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

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

您需要在控件中将DropDownList公开为公共。 这样,您的页面可以侦听事件并做出响应。 例如:

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
}

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

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

我认为即使对于DropDownList,您也只需要OnSelectedIndexChanged

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

祝好运!

您只需要将事件从用户控件冒泡到父页面。 这是有关此主题的问题 ,并提供了一篇文章介绍如何执行此操作

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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