Access Master Page Control - asp.net

I am using a UserControl Which is present in the Master Page. I need to access a Master page control in the UserControl. I need your suggestions.
The Scenario is A label is present in the Master Page. Based upon selections in the usercontrol i need to modify the masterpage label. The UserControl is present in the Master page itself not in the content place holder.

Create a public method (or public property) in the master page to modify your label and in the UserControl you are able to call it, through the Page.master object:
YourMasterPageClass master = Page.master as YourMasterPageClass;
if(master != null)
{
master.YourEditMethod("hello");
}

Quick and Easy way is to create event in control and handle in master like this:
//Control aspx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs"
Inherits="TestControl" %>
<div style="width:300px;border:2px groove blue;">
<asp:Button ID="btn1" runat="server" Text="One" onclick="btn_Click" />
<asp:Button ID="btn2" runat="server" Text="Two" onclick="btn_Click" />
<asp:Button ID="btn3" runat="server" Text="Three" onclick="btn_Click" />
<asp:Button ID="btn4" runat="server" Text="Four" onclick="btn_Click" />
</div>
//Control C#
namespace Controls
{
public partial class TestControl : System.Web.UI.UserControl
{
public delegate void UserChoice(TestEventArgs e);
public event UserChoice OnUserChoice;
protected void btn_Click(object sender, EventArgs e)
{
if (OnUserChoice != null)
OnUserChoice(new TestEventArgs(((Button)sender).Text));
}
}
public class TestEventArgs : EventArgs
{
private string _value;
public TestEventArgs(string str)
{
_value = str;
}
public string Message
{
get { return _value; }
}
}
}
//MasterPage Code
protected void Page_Load(object sender, EventArgs e)
{
test1.OnUserChoice += new
Controls.TestControl.UserChoice(test1_OnUserChoice);
}
void test1_OnUserChoice(ROMS.Intranet.Controls.TestEventArgs e)
{
MasterLabel.Text = e.Message;
}
MasterLabel is name of the label in master page.
test1 is the control in master page.

Related

How can I Implement N level nested Repeater control in asp.net?

I want to achieve n level data hierarchy in using repeater control in asp.net.
Is there any solution to achieve that hierarchy ?
For this answer I'm going to suggest creating your template programmatically - see here: https://msdn.microsoft.com/en-us/library/aa289501 .
There is probably some way to use templates that have been created in markup, but this seems easier, and definitely more flexible.
I start out with a page with just a repeater (not template)
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater runat="server" ID="TestRepeater">
</asp:Repeater>
</div>
</form>
</body>
and a data class
public class DataClass
{
public string Name { get; set; }
public List<DataClass> Children { get; set; }
}
For the template we use the following class:
public class DataTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var name = new Literal();
var repeater = new Repeater();
name.DataBinding += BindingLiteral;
repeater.DataBinding += BindingRepeater;
// this here makes it recursive
repeater.ItemTemplate = new DataTemplate();
container.Controls.Add(name);
container.Controls.Add(repeater);
}
private void BindingLiteral(object sender, System.EventArgs e)
{
var name = (Literal)sender;
var container = (RepeaterItem)name.NamingContainer;
name.Text = String.Concat("<h2>", DataBinder.Eval(container.DataItem, "Name").ToString(), "</h2>");
}
private void BindingRepeater(object sender, System.EventArgs e)
{
var name = (Repeater)sender;
var container = (RepeaterItem)name.NamingContainer;
name.DataSource = DataBinder.Eval(container.DataItem, "Children");
}
}
Obviously you'll want to use a more sophisticated template. Notice that if you currently have a template in markup, you could simply take the code that has been generated by the markup parser, and adapt it to your needs.
Now in the code behind of the page we simple assign the ItemTemplate and DataSource:
public partial class Test : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
TestRepeater.DataSource = GetTestData();
TestRepeater.ItemTemplate = new DataTemplate();
TestRepeater.DataBind();
}
}
Nice thing about this is your template is just a class, so you could add a public Int32 Depth { get; set; } to it, and change the generated controls based on your depth.
Another solution, without creating the template programmatically :
Using a simple data class :
public class DataClass
{
public string Name { get; set; }
public List<DataClass> Children { get; set; }
}
In the ASPX markup create your parent repeater, put your item display code in the ItemTemplate, and add a second "empty" repeater :
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater runat="server" ID="ParentRepeater" OnItemDataBound="Repeater_ItemDataBound">
<ItemTemplate>
<asp:Literal runat="server" Text="<%# Eval("Name") %>"></asp:Literal>
<asp:Repeater runat="server" ID="ChildRepeater" OnItemDataBound="Repeater_ItemDataBound" Visible="false">
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
And in the code-behind :
protected void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e) {
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
DataClass currentItem = (DataClass)e.Item.DataItem;
if (currentItem.Children.Count > 0) {
Repeater ChildRepeater = (Repeater)e.Item.FindControl("ChildRepeater");
ChildRepeater.DataSource = currentItem.Children;
ChildRepeater.ItemTemplate = ParentRepeater.ItemTemplate;
ChildRepeater.Visible = true;
ChildRepeater.DataBind();
}
}
}

Calling method in parent from user control

For some business related reasons I made a wizard navigation user control. Pretty simple: Next/Previous/Finish buttons.
Each of the parent pages that use this nav user control have a SaveData function, which saves the data and does a bunch of other stuff.
When the user clicks Next/Previous/Finish I want to call the parent's SaveData function before redirecting to the other page. How should I do this or can you recommend a better way (code examples if possible please)?
Thanks in advance!
UserControl should not call Parent's function. It is not a good design.
Instead, you want to bubble up the event from UserControl to the Parent page.
Note: my project's namespace is DemoWebForm.
MyUserControl.ascx
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="MyUserControl.ascx.cs"
Inherits="DemoWebForm.MyUserControl" %>
<asp:Button runat="server" ID="NextButton"
OnClick="NextButton_Click" Text="Next" />
<asp:Button runat="server" ID="PreviousButton"
OnClick="PreviousButtonn_Click" Text="Previous" />
<asp:Button runat="server" ID="FinishButton"
OnClick="FinishButton_Click" Text="Finish" />
MyUserControl.ascx.cs
public partial class MyUserControl : System.Web.UI.UserControl
{
public event ClickEventHandler NextClicked;
public event ClickEventHandler PreviousClicked;
public event ClickEventHandler FinishClicked;
protected void NextButton_Click(object sender, EventArgs e)
{
if (NextClicked != null)
{
NextClicked(sender, e);
}
}
protected void PreviousButtonn_Click(object sender, EventArgs e)
{
if (PreviousClicked != null)
{
PreviousClicked(sender, e);
}
}
protected void FinishButton_Click(object sender, EventArgs e)
{
if (FinishClicked != null)
{
FinishClicked(sender, e);
}
}
}
Parent.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Parent.aspx.cs"
Inherits="DemoWebForm.Parent" %>
<%# Register Src="MyUserControl.ascx" TagName="MyUserControl" TagPrefix="uc1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<uc1:MyUserControl ID="MyUserControl1" runat="server"
OnNextClicked="MyUserControl1_NextClicked"
OnPreviousClicked="MyUserControl1_PreviousClicked"
OnFinishClicked="MyUserControl1_FinishClicked" />
<asp:Literal runat="server" ID="MessageLiteral" />
</form>
</body>
</html>
Parent.aspx.cs
public partial class Parent : System.Web.UI.Page
{
protected void MyUserControl1_NextClicked(object sender,EventArgs e)
{
MessageLiteral.Text = "Next button was clicked";
}
protected void MyUserControl1_PreviousClicked(object sender, EventArgs e)
{
MessageLiteral.Text = "Previous button was clicked";
}
protected void MyUserControl1_FinishClicked(object sender, EventArgs e)
{
MessageLiteral.Text = "Finish button was clicked";
}
}
you only need the delegate:
public delegate void ClickEventHandler(object sender, EventArgs e);
public event ClickEventHandler NextClicked;

How to Add One event to each Item On A CheckboxList Asp.net

How Can I Add One Event to Each item On A CheckBoxList, pr example I Wanto to add One Click Event to check What Item Has been checked.
thanks in advance.
Each item in CheckBoxList is of type System.Web.UI.WebControls.ListItem and has no events defined.
That's a bit tricky with the CheckBoxList. Don't think there's a straight way to add an click-event to each item, since the ListItem-class doesn't have any events.
You could set AutoPostBack="true" on the CheckBoxList and check on page load which items are selected, but you wouldn't know easy which was the last one clicked.
Other solution is to get rid of the CheckBoxList and create just CheckBoxes and set the click-event on those to the same event-method. And there you could check the sender.
ASPX:
<asp:CheckBox ID="CheckBox1" Text="A" OnCheckedChanged="CheckBox_Clicked" AutoPostBack="true" runat="server" />
<asp:CheckBox ID="CheckBox2" Text="B" OnCheckedChanged="CheckBox_Clicked" AutoPostBack="true" runat="server" />
<asp:CheckBox ID="CheckBox3" Text="C" OnCheckedChanged="CheckBox_Clicked" AutoPostBack="true" runat="server" />
Code behind:
void CheckBox_CheckedChanged(object sender, EventArgs e)
{
Console.WriteLine(((CheckBox)sender).Text);
}
Or you could make your own custom CheckBoxList that handles click-events on items.
OK. So I found this question/answer and it didn't help me out. While the provided answer is correct, there is an easy way to build a CheckBoxList-like control witha Repeater control.
Turns out that you can use a Repeater with an ItemTemplate with a CheckBox.
I have a complete explanation here: http://www.rhyous.com/2014/10/17/aspx-checkboxlist-alternative-that-allows-for-the-oncheckedchanged-event/
I also copied the needed data here in this answer:
Default.aspx
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckBoxListExample._Default" %>
<%# Import Namespace="CheckBoxListExample" %>
<%# Import Namespace="CheckBoxListExample.Models" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:CheckBox ID="cb1" runat="server" AutoPostBack="true" OnCheckedChanged="RepeaterCheckBoxChanged"
Text="<%# ((CheckBoxViewModel)Container.DataItem).Name %>"
Checked="<%# ((CheckBoxViewModel)Container.DataItem).IsChecked %>" />
</ItemTemplate>
</asp:Repeater>
</div>
</asp:Content>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using CheckBoxListExample.Models;
namespace CheckBoxListExample
{
public partial class _Default : Page
{
private List<CheckBoxViewModel> _ViewModels;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var _ViewModels = new List<CheckBoxViewModel>
{
new CheckBoxViewModel {Name = "Test1", IsChecked = true},
new CheckBoxViewModel {Name = "Test2"},
new CheckBoxViewModel {Name = "Test3"}
};
Repeater1.DataSource = _ViewModels;
Repeater1.DataBind();
}
}
protected void RepeaterCheckBoxChanged(object sender, EventArgs e)
{
var cb = sender as CheckBox;
if (cb == null) return;
if (cb.Checked)
{
// Insert
}
else
{
// Delete
}
}
}
}
CheckBoxViewModel
namespace CheckBoxListExample.Models
{
public class CheckBoxViewModel
{
public string Name { get; set; }
public bool IsChecked { get; set; }
}
}

Adding and removing User control from Placeholder

What I am trying to achieve that if a user control already added to placeholder then it will be removed otherwise will be added to it and it will be done in a LinkButton's onclick.
The code:
public partial class SiteSettings : System.Web.UI.Page {
private UserSettings UserSettingsControl;
protected void Page_Load(object sender, EventArgs e) {
System.Diagnostics.Debug.WriteLine("Pageload");
UserSettingsControl = LoadControl("~/UserControls/UserSettings.ascx") as UserSettings;
}
protected void UserLink_Click(object sender, EventArgs e) {
if (SettingsPlaceholder.Controls.Contains(UserSettingsControl)) {
System.Diagnostics.Debug.WriteLine("Contains");
SettingsPlaceholder.Controls.Remove(UserSettingsControl);
} else {
System.Diagnostics.Debug.WriteLine("Does not Contains");
SettingsPlaceholder.Controls.Add(UserSettingsControl);
}
}
}
Now it is not working. And I am getting:
Pageload // on first time load
Pageload // on first time click
Does not Contains // on first time click
Pageload // on second time click
Does not Contains // on second time click
in the Output window.
How can I achieve this? I also tried to store it into ViewState, but since UserControl is not serializable so that didn't worked.
The aspx page is:
<telerik:RadAjaxManager ID="AjaxManager" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="UserLink">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="SettingsPanel" LoadingPanelID="LoadingPanel" UpdatePanelRenderMode="Block" />
<telerik:AjaxUpdatedControl ControlID="PlaceHolderPanel" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
<ClientEvents OnResponseEnd="respondEnd" />
</telerik:RadAjaxManager>
<asp:Panel ID="SettingsPanel" runat="server">
<telerik:RadSplitter ID="MainSplitter" runat="server" MinHeight="200" Width="100%"
OnClientLoaded="splitterLoaded" OnClientResized="splitterLoaded">
<telerik:RadPane ID="LeftPane" runat="server" MaxWidth="250" Width="150" MinWidth="150" CssClass="left-rounded-corner settings-splitter-left">
<asp:Panel runat="server">
<asp:LinkButton ID="UserLink" runat="server" onclick="UserLink_Click" Text="User Settings" />
</asp:Panel>
</telerik:RadPane>
<telerik:RadSplitBar ID="Splitbar" runat="server" CollapseMode="Forward" />
<telerik:RadPane ID="RightPane" runat="server" CssClass="right-rounded-corner settings-splitter-right">
<asp:Panel ID="PlaceHolderPanel" runat="server" Height="100%">
<asp:PlaceHolder runat="server" ID="SettingsPlaceholder" />
</asp:Panel>
</telerik:RadPane>
</telerik:RadSplitter>
</asp:Panel>
<telerik:RadAjaxLoadingPanel ID="LoadingPanel" runat="server" />
Edit:
Modified code:
public partial class SiteSettings : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
AddUserSettings();
}
}
public UserControl UserSettingsControl {
get {
if (ViewState["UserSettings"] == null) {
ViewState["UserSettings"] = LoadControl("~/UserControls/UserSettings.ascx") as UserSettings;
}
return (UserControl)ViewState["UserSettings"];
}
}
public UserControl SpaceSettingsControl {
get {
if (ViewState["SpaceSettings"] == null) {
ViewState["SpaceSettings"] = LoadControl("~/UserControls/SpaceSettings.ascx") as SpaceSettings;
}
return (UserControl)ViewState["SpaceSettings"];
}
}
protected void SettingsLink_OnCommand(object sender, CommandEventArgs commandEventArgs) {
switch (commandEventArgs.CommandName) {
case "User":
AddUserSettings();
break;
case "Space":
AddSpaceSettings();
break;
}
}
private void AddUserSettings() {
AddSettings(UserSettingsControl);
}
private void AddSpaceSettings() {
AddSettings(SpaceSettingsControl);
}
private void AddSettings(UserControl control) {
SettingsPlaceholder.Controls.Add(control);
}
}
Create a Property in your WebForm like below.
public UserSettings UserSettingsControl
{
get
{
if (Session["MyControl"] == null)
Session["MyControl"] =
LoadControl("~/UserControls/UserSettings.ascx") as UserSettings;
return (UserSettings)Session["MyControl"];
}
}
Now you can access the memory of UserSettingsControl. As it will persist across the Postback. In the original code, the UserSettingsControl was being reset to null across PostBack.
By end of the Page Life Cycle all the controls created at runtime
will be disposed. Finally, you cannot find the control created at
runtime after Postback. Only Recreation of the same control will be
required on each PostBack.
You could just not use a PlaceHolder and have the control there the whole time. Then the linkButton could toggle the visibility of the control.
The main problem is that the you are adding the control to the page linkButton click. Dynamically added controls work best when added in the Page_Init and Page_PreInit this allows them to maintain their ViewState. Also they have to be added to the placeholder on every postback. If in your example another control causes a postback after the SettingsControl is added to the placeholder, then the SettingsControl will disappear because it is not being added on every postback.

ASP.NET how to access public properties?

I have two pages page1.aspx and page2.aspx, both have code behind with partial classes.
How do i access public property message on page1.aspx from page2.aspx ?
public string message { get; set; }
Update
I just read that the one is MasterPage and the other is the client to masterpage ?
then its diferent way.
Page to Page
If you have 2 simple diferent pages.
I have done it this way.
Its a post value, by using asp.net tricks :)
On Page2.aspx add this on top.
<%# PreviousPageType VirtualPath="Page1.aspx" %>
and how I read from Page1.aspx on code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Page.PreviousPage != null)
{
if(Page.PreviousPage.IsCrossPagePostBack == true)
{
txtGetItFromPreviusPage.Text = PreviousPage.SomeString;
}
}
}
}
On Page1.aspx
the button that send me to Page2.aspx
<asp:Button ID="btnEna" runat="server" Text="Send Some variables to other page"
PostBackUrl="Page2.aspx"
onclick="btnMoveSelection_Click" />
and the code that I use for Page1 calculations or other thinks
public string SomeString
{
set
{
ViewState["txtSomeString"] = value;
}
get
{
if (ViewState["txtSomeString"] != null)
return ViewState["txtSomeString"].ToString();
else
return string.Empty;
}
}
protected void btnMoveSelection_Click(object sender, EventArgs e)
{
// some final calculations
}
If the one is the Master page, and the other is the page that use the master.
The Master Page
<body>
<form id="form1" runat="server">
<div>
<asp:Literal runat="server" ID="txtOnMaster"></asp:Literal>
<br />
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
and the code behind
public partial class Dokimes_StackOverFlow_MasterPage : System.Web.UI.MasterPage
{
public string TextToMaster
{
get { return txtOnMaster.Text; }
set { txtOnMaster.Text = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
// here I find the control in the client page
Control FindMe = ContentPlaceHolder1.FindControl("txtOut");
// and if exist I set the text to client from the master
if (FindMe != null)
{
((Literal)FindMe).Text = "Get from Master Page";
}
}
}
and now the Page1.aspx that have the previus master page
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Literal runat="server" ID="txtOut"></asp:Literal>
</asp:Content>
and the code
protected void Page_Load(object sender, EventArgs e)
{
// here I set the text on master page from client
((Dokimes_StackOverFlow_MasterPage)Master).TextToMaster = "Set from Client";
}
If you are NOT in a sessionless environment, then in the transmitter page, push your string (or your object - e.g., a Dictionary ) into session:
Session("MyVar") = "WhatEver"
In the receiver page, you can get it back with:
MyPreviousVar = Session("MyVar")
If you want a message property on every page. You could implement your own BasePage and define the message property in your base page. Then derive subsequent pages from your custom base page. That way all of your pages will always have a message property.
However, this isn't going to keep the message property constant through out each page. If you are trying to pass values between pages then you should use either session state or a querystring
This MSDN page may be of use to you.
You shouldn't really be doing this, pages should be standalone entities. If you need to pass this data from one form to another, consider using the querystring, or posting your form to the second page.
OK. Have you tried then Page.Master.Property?

Resources