Search code examples
c#asp.netmaster-pages

Pass master page control values on content page on page_load


I have a dropdowlist on master page and I want to pass the selected value on content pages when a content page loads. My problem is that the value passes only when I change value on the dropdownlist. So when a page load I have to reselect from dropdownlist to capture the value of the dropdown. If I am browsing the content pages the selected value doesnt pass on page load. My master page code .net:

<asp:DropDownList ID="ddlcategories" 
        runat="server" DataSourceID="SqlDataSourcecategories" DataTextField="CategoryName" 
        DataValueField="CategoryID" AutoPostBack="True" 
        onselectedindexchanged="ddlcategories_SelectedIndexChanged"></asp:DropDownList>

Master page cs:

protected void Page_Load(object sender, EventArgs e)
{
 if (!IsPostBack)
 {    
      ddlcategories.DataBind();
      ddlcategories.Items.Insert(0, "Uncategorized");
      ddlcategories.Items[0].Value = "0";
      ddlcategories.SelectedValue = Convert.ToString(Session["lblCategoryID"]);
  }
}
protected void ddlcategories_SelectedIndexChanged(object sender, EventArgs e)
{
    Session["lblCategoryID"] = Convert.ToInt32(ddlcategories.SelectedValue);
}

Content page cs:

protected void Page_Load(object sender, EventArgs e)
{                
    Label10.Text = Convert.ToString(((DropDownList)Master.FindControl("ddlcategories")).SelectedValue);                 
}

Solution

  • Try this solution:

    Master page:

    <asp:DropDownList ID="ddlcategories" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlcategories_SelectedIndexChanged">
        <asp:ListItem>One</asp:ListItem>
        <asp:ListItem>Two</asp:ListItem>
    </asp:DropDownList>
    

    Master page CS:

    public string SelectedValue
    {
        get
        {
            return ddlcategories.SelectedValue;
        }
        set
        {
            ddlcategories.SelectedValue= value;
        }
    }
    
    protected void ddlcategories_SelectedIndexChanged(object sender, EventArgs e)
    {
        SelectedValue = ddlcategories.SelectedValue;
    }
    

    Content Page markup:

    <%@ MasterType VirtualPath="~/Site1.Master" %>
    
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    

    Content page CS.

    protected void Page_PreRender(object sender, EventArgs e)
    {
        Label1.Text = Master.SelectedValue;
    }
    

    Note: Values are just to demonstrate, you can use the actual data source values in drop down.