Adding User-Control when clicking a button - asp.net

I created a user-control (customized calendar - but it doesn't matter).
In addition, I have a button control, and my target is to add to the page the calendar (the user-control) when clicking on the button. The number of calendars in the page is unlimited, I do not want to add only one calendar to the page.
protected void addCalendar_Click(object sender, EventArgs e)
{
// clicked on button, should add the user control.
}
The user-control is already registered on the page:
<%# Register src="CalendarUserControl.ascx" tagname="CalendarUserControl" tagprefix="uc" %>
Each calendar should be appended to the following div (this div is defined in the aspx page):
<div id="calendars-holder">
// first calendar appended
// second calendar appended
// and so on..
</div>

protected int countCalendars;
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["countCalendars"] != null)
countCalendars = (int) ViewState["countCalendars"];
// init
if (!IsPostBack)
countCalendars = 0;
// register existing user-controls; won't occur before onclick button
// so ViewState["countCalendar"] will be exist.
for (int i = 0; i < countCalendars; i++)
addCalendar(i);
}
// onclick button
protected void addCalender_Click(object sender, EventArgs e)
{
addCalendar(countCalendars++);
ViewState["countCalendars"] = countCalendars;
}
// Adding a new User-Control
protected void addCalendar(int idNumber)
{
CalculatorUserControl Calendar = LoadControl("~/CalendarUserControl.ascx") as CalendarUserControl;
Calendar.ID = "CalculatorUserControl" + idNumber.ToString();
PlaceHolder1.Controls.Add(Calendar);
}

Related

How to check which control fired in Master Page

How can we find the control that fired inside of a Master page that also has a panel from code behind?
I have the following layout.
Master Page
+---------Panel-----------+
| TextBox Button1 Button2|
+-------------------------+
|
-------->Child Page
+-------------------------+
| Get From Here! |
+-------------------------+
When I try the following the targetId is empty
if (IsPostBack)
{
var targetID = Request.Form["__EVENTTARGET"];
if (targetID != null && targetID != string.Empty)
{
var targetControl = this.Page.FindControl(targetID);
}
}
I want to find out which button caused post back.
****Update****
I've tried the following link below without sucess.
Find on Page Init
You can use an event that your MasterPage offers to communicate with the Page.
Within your MasterPage create something like these
public event EventHandler Button1ClickEvent;
public event EventHandler Button2ClickEvent;
What is going on here is that you are creating an event that the MasterPage can check for a page that is listening for and fire an event to that page to signal that is has been called. In this case EventHandler means that you'll be passing EventArgs to the event listener.
You send an event by doing this
protected void Button1_Click(object sender, EventArgs e)
{
if (Button1ClickEvent != null) // check if a sub page is implementing it
Button1ClickEvent(this, EventArgs.Empty); // fire the event off
}
protected void Button2_Click(object sender, EventArgs e)
{
if (Button2ClickEvent != null)
Button2ClickEvent(this, EventArgs.Empty);
}
Next, wire up your Page to implement these events
Add in this to your Page definition
<%# MasterType VirtualPath="~/MasterPage.master" %>
Now you can access these events in your page code-behind
private void Master_Button1Click(object sender, EventArgs e)
{
// This is called when the `Button1ClickEvent` is fired from your MasterPage
}
private void Master_Button2Click(object sender, EventArgs e)
{
// This is called when the `Button2ClickEvent` is fired from your MasterPage
}
protected void OnInit(EventArgs e)
{
// Setup an event handler for the buttons
Master.Button1ClickEvent += new EventHandler(Master_Button1Click);
Master.Button2ClickEvent += new EventHandler(Master_Button2Click);
}

Submit is not working

I'm using dynamic controls at my ASP.NET applications. So the issue is - when I use these controls separatelly - they work well. But when I put these two controls on the same page - ONLY LAST submit event is fired. Could anyone help me to identify where is the issue and how to fix it?
Here is my aspx layout:
<%# Control Language="C#" AutoEventWireup="True" CodeBehind="MYPAGE.ascx.cs" Inherits="MYNAMESPACE" %>
<%# Register Assembly="MYANOTHERNAMESPACE" Namespace="MYNAMESPACE" TagPrefix="DAControl" %>
...
<div>
<DAControl:ChooseImageDialog runat="server" id="ChooseImageDialog" />
<DAControl:ChooseVideoDialog runat="server" id="ChooseVideoDialog" />
</div>
Here is my 1st control:
[ToolboxData("<{0}:ChooseImageDialog runat=server></{0}:ChooseImageDialog>")]
public class ChooseImageDialog : WebControl
{
/* This is only part of my code, which should enough for explaining the issue*/
private Button applyPreview = new Button();
private Button cancelPreview = new Button();
protected override void OnLoad(EventArgs e)
{
applyPreview.Click += new EventHandler(applyPreview_Click);
base.OnLoad(e);
}
void applyPreview_Click(object sender, EventArgs e)
{
// I want to reach this block
}
}
}
Here is my 2nd control:
[ToolboxData("<{0}:ChooseVideoDialog runat=server></{0}:ChooseVideoDialog>")]
public class ChooseVideoDialog : WebControl
{
/* This is only part of my code, which should enough for explaining the issue*/
private Button applyVideoPreview = new Button();
private Button cancelPreview = new Button();
protected override void OnLoad(EventArgs e)
{
applyVideoPreview.Click += new EventHandler(ApplyPreviewVideo_Click);
base.OnLoad(e);
}
void ApplyPreviewVideo_Click(object sender, EventArgs e)
{
// I want to reach this block
}
}
Events must be wired up in the Init event. Any later in the life cycle is too late.

Preserving user control on autopostback asp.net

I have two user controls: dsucTopLeft and dsucTopRight in an aspx page. Each of the user controls has a dropdownlist to select values from.
The aspx page has a button "Save".
In the OnClickEvent of the button, I take data from those user controls (which return the values from the drop down list). I need to insert these values into database. However, these values set to 0 after the button is clicked.
How would I preserve those values?
Code:
ParentTemplate.aspx
<div class="leftDashboard">
<uc:dsuc ID="dsucTopLeft" runat="server" />
</div>
<div id="rightDashboard">
<uc:dsuc ID="dsucTopRight" runat="server" />
</div>
It also has a button:
<asp:Button ID="SaveButton" runat="server" OnClick="SaveButton_Click" Text="Save Dashboard" />
This is the codebehind for the button:
protected void SaveButton_Click(object sender, EventArgs e)
{
//If the mode is "CREATE", then it needs to insert the information about dashboard and the charts it contains
for (int i = 0; i < dsuc.Length; i++)
{
dsuc[i].dashboardId = dashboardId;
if (dsuc[i].chartId != 0) //Here, the chartId remains 0
dsuc[i].insert();
}
}
dsuc is an array. It is being populated in the following way:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dsuc[0]=dsucTopLeft;
dsuc[1]=dsucTopRight;
}
}
UserControl:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
initializeDropDownList();//It initializes the drop down list
}
}
public void insert()
{
//It inserts into database
}
protected void chartDDLSelectedIndexChanged(object sender, EventArgs e)
{
oldChartId = chartId;
String chartTitle = chartDropDownList.SelectedItem.Text;
if (chartTitle != dropDownMessage)
{
chartId = int.Parse(chartDropDownList.SelectedItem.Value);
//Chart user control should be retrieved from the database and drawn.
chartTitleLabel.Text += "chart id : " + chartId.ToString() + " title: " + chartTitle;
//chartUserControl.Visible = true;
}
}
The user control i.e. the class of dsuc[] changes its chartId when an item in its drop down list is selected. I printed the value, it works. But that same value becomes 0 when the button in clicked.
Remove the if (!Page.IsPostBack)from
if (!Page.IsPostBack)
{
dsuc[0]=dsucTopLeft;
dsuc[1]=dsucTopRight;
}
If not, it will only populate it when is not post back. As a click produces a post back, you'll want that code being executed :)
Also, it is probably that your clickp event is being called beforeselectedindexchanged`. In that case, the code that sets chartId is not executed (yet) when the click event is fired. You can solve that doing this:
public int ChartId { get { return int.Parse(chartDropDownList.SelectedItem.Value); }}
and calling that property instead. Also, you can use that property in your selectedindexchanged event handler

Handle Button Click Event from User Control loaded dynamically

I have a blank user control (child) and during Page_Load i create some text boxes and a button. I also add an event to the button.
I then load that user control dynamically from a placeholder in another usercontrol (parent).
Both controls are rendered correctly but when i click on the button, the event isnt fired.
Any ideas on how to handle the event?
Child code:
protected void Page_Load(object sender, EventArgs e)
{
/*... other user controls ..*/
UpdateButton = new LinkButton();
UpdateButton.ID = "buttonid";
UpdateButton.Text = "text";
UpdateButton.Click += new EventHandler(UpdateButton_Click);
this.Controls.Add(UpdateButton);
}
protected override void Render(HtmlTextWriter writer)
{
for (int i = 0; i < this.Controls.Count; i++)
{
this.Controls[i].RenderControl(writer);
}
}
public void UpdateButton_Click(object sender, EventArgs e)
{
//Do stuff
}
Parent code:
protected void Page_Load(object sender, EventArgs e)
{
placeholder.Controls.Clear();
ChildControl uc = (ChildControl)LoadControl("~/UserControls/ChildControl.ascx");
placeholder.Controls.Add(uc);
}
If i use the child control directy (ie without the parent the control) the click event is raised and handled nicely. But when i use the parent control, the debugger wont even hit a breakpoint inside UpdateButton_Click().
Thanks in advance.
I think I know what might be happening. In your parent Page_Load you are calling placeholder.Controls.Clear(); This does what you would imagine and clears the control, including any events that have occurred. What happens when remove this line? Do you get an additional one created on each postback?

Pass MasterPage ImageButton event to content Page

I have ImageButton in a MasterPage. I want the OnClick event to fire and be captured by the .ASPX page hosted inside the MasterPage?
MasterPage:
<asp:ImageButton ID="btnClear" OnClick="Clear_Click"
ImageUrl="images/Back_Icon_06.png" runat="server" AlternateText="Clear"
width="38" height="39"/>
The masterpage is actually a child of the page (in fact, it's a UserControl). We don't want the page to have to be aware of the intimate details of its child controls (thats why we delegate those aspects to those controls in the first place), so the correct approach would be to handle the click event on the master page and from there fire another event on the masterpage which the page handles:
Master:
public event EventHandler SomethingHappened;
protected void Button_Click(object sender, EventArgs e)
{
OnSomethingHappened(EventArgs.Empty);
}
protected void OnSomethingHappened(EventArgs e)
{
if(this.SomethingHappened != null)
{
this.SomethingHappened(this, e);
}
}
Page:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//allows us to change master pages
if(this.Master is MyMaster)
{
((MyMaster)this.Master).SomethingHappened += new EventHandler(HandleSomethingHappened);
}
}
private void HandleSomethingHappened(object sender, EventArgs e)
{
//deal with it
}
I would recommend specifying a strongly typed master page in your content page and exposing the event on the master page side
Here's a good MSDN reference
This is similar to what Rex M specified but just simplifies accessing the Master Page a little bit.
// Master Page Code
public event EventHandler ClearClick
{
add
{
this.btnClear.Click += value;
}
remove
{
this.btnClear.Click -= value;
}
}
// Content Page markup
<%# Page masterPageFile="~/MasterPage.master"%>
<%# MasterType virtualPath="~/MasterPage.master"%>
// Content Page Code
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.Master.ClearClick += new EventHandler(OnClearClick);
}
private void OnClearClick(object sender, EventArgs e)
{
// Handle click here
}

Resources