A confusion about webcontrol scope in ASP.NET - asp.net

A custom control inside my Masterpage, Does that can access the main page?
Please help!
This is my code.
namespace TVSSystem
{
public partial class ControlTVS1 : System.Web.UI.UserControl
{
Page abc;
protected void Page_Load(object sender, EventArgs e)
{
abc = this.Page; //Control: I suposse that I can access all controls of my page
}
protected void Image1_Click(object sender, ImageClickEventArgs e)
{
ContentPlaceHolder cph = (ContentPlaceHolder)abc.FindControl("ContentPlacerHolder1");
TextBox txt = (TextBox)cph.FindControl("TextBox1");
Button btn = (Button)cph.FindControl("Button3");
txt.Visible = true;
btn.Visible = true;
}
}
}
Solved.
http://forums.asp.net/t/1000865.aspx/1

You could use the Page property to access the page containing this user control (no matter if you placed it inside a masterpage):
public partial class WebUserControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
var page = this.Page;
...
}
}

Related

Dynamic Control creation, event handling and control properties in asp.net

I am trying to solve the following issue:
I have a user control that needs to be dynamically loaded inside another control. This dynamically loaded control raises an event and as per my knowledge the events raised by dynamically loaded control will only be handled correctly if the control is created and loaded during the onload event. There is one more constraint that i have to consider when loading the control dynamically and that is a property in parent control. This property will determine if the control should be loaded or not.
Pseudo Code:
ControlA
Property ShowControl
ControlA has a CheckBox(chkShowControlIfSelected)
OnLoadEvent()
If chkShowControlIfSelected.checked checked and ShowControlProperty is set
{
reate ControlB Dynamically
ControlB.Event += EventHandler()
Add ControlB to ControlCollection
}
The problem i am running into is that if I include the code to load the controlB in prerender event then the property ShowControl is set correctly but the EventHandler() is not called. If I put the code to load the controlB dynamically in pageLoad event then property ShowControl is not yet set but in that case the eventHandler Code is called correctly.
Am i missing something or handling the code in incorrect event handlers?
Following is the working example:
ControlA:
public partial class ControlA : System.Web.UI.UserControl
{
public bool ShowControl
{
get
{
if (this.ViewState["ShowControl"] == null)
return false;
else
return (bool)this.ViewState["ShowControl"];
}
set
{
this.ViewState["ShowControl"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (this.ShowControl)
{
var controlB = (ControlB)this.LoadControl("ControlB.ascx");
controlB.FileUploadingComplete += controlB_FileUploadingComplete;
this.pnl1.Controls.Add(controlB);
}
}
void controlB_FileUploadingComplete(object sender, EventArgs e)
{
//throw new NotImplementedException();
Trace.Write("file upload completed");
}
}
ControlB:
public partial class ControlB : System.Web.UI.UserControl
{
public event EventHandler FileUploadingComplete;
protected void OnFileUploadingComplete()
{
if (this.FileUploadingComplete != null)
this.FileUploadingComplete(this, EventArgs.Empty);
}
protected void btn1_Click(object sender, EventArgs e)
{
this.OnFileUploadingComplete();
}
}
Page (has ControlA present):
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.ControlA1.ShowControl = true;
}
}

Update controls field when page load

I fill some controls with data from data base, by calling a select method
and I change the values to update it, but when I press update button, it takes the values that called at the page load, and ignore all changes.
how can I avoid this ?
thanks in advance : )
here is a simple code to present my problem
SelectBLL _selectbll;
string _title = string.Empty;
string _details = string.Empty;
#region Page Load
protected void Page_Load(object sender, EventArgs e)
{
GetUMedicineDetails();
}
#endregion
#region Get UMedicine Details
private void GetUMedicineDetails()
{
_selectbll = new SelectBLL();
_selectbll._GetUMedicineDetails(Request.QueryString[0].ToString(), ref _title, ref _details);
#region Bind Controls
txtdetails.Text = _details;
txttitle.Text = _title;
#endregion
}
#endregion
#region Update Button
protected void btnupdate_Click(object sender, EventArgs e)
{
_UpdateUMedicine();
}
#endregion
#region UpdateU Medicine
public void _UpdateUMedicine()
{
_updatebll = new UpdateBLL();
_updatebll._UpdateUMedicine(
Convert.ToInt32(Request.QueryString[0]), txtdetails.Text, txttitle.Text);
}
#endregion
Page.IsPostBack Property: Gets a value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetUMedicineDetails();
}
}
Also, Refer:
How to: Determine How ASP.NET Web Pages Were Invoked
DataBind only if !Page.IsPostaBack:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostaBack)
GetUMedicineDetails();
}

How to call a page method in the dynamically addedded usercontrol?

I am adding a user control dynamically on a page, the user control has a save button that takes data from both user control and page to save in the DB, in the same save method i want to access a method wrriten in the page, so i that mehod had code to rebind the grid kept in the page.
So how can i call a page method in the dynamically added user control?
I was going to suggest creating a base class for your pages, but found an even better way to accomplish this task:
http://www.codeproject.com/Articles/115008/Calling-Method-in-Parent-Page-from-User-Control
Control code:
public partial class CustomUserCtrl : System.Web.UI.UserControl
{
private System.Delegate _delWithParam;
public Delegate PageMethodWithParamRef
{
set { _delWithParam = value; }
}
private System.Delegate _delNoParam;
public Delegate PageMethodWithNoParamRef
{
set { _delNoParam = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnMethodWithParam_Click(object sender, System.EventArgs e)
{
//Parameter to a method is being made ready
object[] obj = new object[1];
obj[0] = "Parameter Value" as object;
_delWithParam.DynamicInvoke(obj);
}
protected void BtnMethowWithoutParam_Click(object sender, System.EventArgs e)
{
//Invoke a method with no parameter
_delNoParam.DynamicInvoke();
}
}
Page code:
public partial class _Default : System.Web.UI.Page
{
delegate void DelMethodWithParam(string strParam);
delegate void DelMethodWithoutParam();
protected void Page_Load(object sender, EventArgs e)
{
DelMethodWithParam delParam = new DelMethodWithParam(MethodWithParam);
//Set method reference to a user control delegate
this.UserCtrl.PageMethodWithParamRef = delParam;
DelMethodWithoutParam delNoParam = new DelMethodWithoutParam(MethodWithNoParam);
//Set method reference to a user control delegate
this.UserCtrl.PageMethodWithNoParamRef = delNoParam;
}
private void MethodWithParam(string strParam)
{
Response.Write(“<br/>It has parameter: ” + strParam);
}
private void MethodWithNoParam()
{
Response.Write(“<br/>It has no parameter.”);
}
}

How to preserve dynamically created controls?

I want to preserve the dynamically created control when postback occurs .
protected void Page_Load(object sender, EventArgs e)
{
}
private void CreateTable()
{
HtmlTableRow objHtmlTblRow = new HtmlTableRow();
HtmlTableCell objHtmlTableCell = new HtmlTableCell();
objHtmlTableCell.Controls.Add(new TextBox());
objHtmlTblRow.Cells.Add(objHtmlTableCell);
mytable.Rows.Add(objHtmlTblRow);
this.SaveControlState();
// this.Controls.Add(mytable);
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateTable();
}
It can be achieved by calling CreateTable() in Page_Load. Is there any alternative way to preserve the control
Thanks
You can add them to a List when you create them and save your List to Session. On postback (Page_Load) load them from your Session to your Page.
the below code should work
protected void Page_PreInit(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CreateTable()
}
public static Control GetPostBackControl(Page thisPage)
{
Control ctrlPostedback = null;
string ctrlName = thisPage.Request.Params.Get("__EVENTTARGET");
if (!String.IsNullOrEmpty(ctrlName))
{
ctrlPostedback = thisPage.FindControl(ctrlName);
}
else
{
foreach (string Item in thisPage.Request.Form)
{
Control c = thisPage.FindControl(Item);
if (((c) is System.Web.UI.WebControls.Button))
{
ctrlPostedback = c;
}
}
}
return ctrlPostedback;
}
The code works from UpdatePanel
Reference:http://www.asp.net/ajax/videos/how-to-dynamically-add-controls-to-a-web-page

Handling User Control Events on Containing Page

I want to have a user control containing a save button.
I want the click event attached to the save button to be handled by the containing page not the user control
Is this possible?
EDIT MORE SPECIFIC
Say I have a page called "Editor Page" and a user control called "Editor Buttons".
On the "Editor Buttons" user control I have a save button (which is a web control). I want the Click event of the save button to be handled by the "Editor Page" rather than the user control.
The reason for this is because I want to specify base pages that implement common behaviour.
This technique is commonly referred to as “event bubbling”.
Here is an exmple:
public partial class Test : System.Web.UI.UserControl
{
public event EventHandler buttonClick;
protected void Button1_Click(object sender, EventArgs e)
{
buttonClick(sender, e);
}
}
Then you can subscribe the event buttonClick at webpage to display the different information .
public partial class Test: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UserControlID.buttonClick+=new EventHandler(UserControlID_buttonClick);
}
protected void UserControlID_buttonClick(object sender, EventArgs e)
{
Response.Write("hello,I am jack.");
}
}
I will assume that you have the code for the UserControl. If that is the case, you can define a Save event in your user control and have it expose the Click event of the save button, either directly, or by internally setting up an event handler and raise the Save event when the button is clicked. That could look something like this in the UserControl:
public event EventHandler Save;
private void SaveButton_Click(object sender, EventArgs e)
{
OnSave(e);
}
protected void OnSave(EventArgs e)
{
// raise the Save event
EventHandler save = Save;
if (save != null)
{
save(this, e);
}
}
UserControl1.ascx
UserControl1.ascx.cs
public partial class UserControl1 : System.Web.UI.UserControl
{
public event EventHandler UserControl1Click;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn1_Click(object sender, EventArgs e)
{
UserControl1Click(sender, e);
}
}
UserControl2.ascx
UserControl1.ascx.cs
public partial class UserControl2 : System.Web.UI.UserControl
{
public event EventHandler UserControl2Click;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn2_Click(object sender, EventArgs e)
{
UserControl2Click(sender, e);
}
}
Then add one Asp.Net Text box(to display user control id) and above two user controls to Aspx page as shown below.
<title>Untitled Page</title>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txt1" runat="server"></asp:TextBox> <br />
<UC1:UC ID="uc1" runat="server" />
<UC1:UC ID="uc2" runat="server" />
</div>
</form>
Now add event handler for each user control to handle button click event of two controls as shown below.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
uc1.UserControl1Click += new EventHandler(uc1_UserControl1Click);
uc2.UserControl2Click += new EventHandler(uc2_UserControl2Click);
}
protected void uc1_UserControl1Click(object sender, EventArgs e)
{
txt1.Text = "User Control 1 Clicked";
}
protected void uc2_UserControl2Click(object sender, EventArgs e)
{
txt1.Text = "User Control 2 Clicked";
}
}
If we click User Control1, text box displays “User Control 1 Clicked” or if we click on User Control2, text box displays “User Control 2 Clicked”.

Resources