How to call a page method in the dynamically addedded usercontrol? - asp.net

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.”);
}
}

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;
}
}

How to add event to custom control that fired when click a button in it?

I want to build custom control consist of html code which shows table, and in the footer of this table I need to add three buttons.
What I did is inherit from WebControl class:
public class MyCustomControl : WebControl {
protected override void RenderContents(HtmlTextWriter output)
{
// using output.Write I write the table in html code
// and I write the three buttons using <input> tag in html not <asp:button> tag
}
}
What I want here is to add three events one to each button I wrote, and those events would be used in the user interface and fired when the proper button clicked:
<asp:MyCustomControl runat="server" id="myCtrl" onButton1Click="Button1_Click" onButton2Click="Button2_Click" />
How can I do this ?
Thanx
**UPDATE1:
The render code in my custom control would be like this:
protected override void RenderContents(HtmlTextWriter output)
{
output.Write("<table> ......");
output.Write("<input id='button1' type='button'>");
output.Write("<input id='button2' type='button'>");
output.Write("<input id='button3' type='button'>");
output.Write(".........</table>");
}
So how would I make 'button1' fire the event on server side?
**UPDATE2:
This is what the code looks like:
public class MyCustomControl : WebControl
{
public Button Button1 = new Button {Text = "Button1"};
public Button Button2 = new Button {Text = "Button2"};
public event EventHandler Button1_Click;
public event EventHandler Button2_Click;
protected override void OnPreRender(EventArgs e)
{
Button1.Click += Button1Click;
Button2.Click += Button2Click;
base.OnPreRender(e);
}
protected override void RenderContents(HtmlTextWriter output)
{
using (var plh = new PlaceHolder())
{
var htmlCode = new StringBuilder();
htmlCode.Append("....html code for table...");
var container = new HtmlGenericControl { InnerHtml = htmlCode.ToString() };
plh.Controls.Add(container);
plh.Controls.Add(Button1);
plh.Controls.Add(Button2);
plh.RenderControl(output);
htmlCode.Append("..../html code for table...");
}
}
private void Button1Click(object sender, EventArgs e)
{
if (Button1_Click != null)
Button1_Click(this, e);
}
private void Button2Click(object sender, EventArgs e)
{
if (Button2_Click != null)
Button2_Click(this, e);
}
And in the page.aspx:
<cc1:MyCustomControl ID="myCtrl" runat="server" onbutton1_click="MyCustomControl_Button1_Click" />
But even with this the button1's click method 'MyCustomControl_Button1_Click' not called.
declare your new events like this:
public event EventHandler OnButton1Click;
public event EventHandler OnButton2Click;
public event EventHandler OnButton3Click;
this in the click method on each button do something like this:
public void Button1_Click(object sender, EventArgs e)
{
if (OnButton1Click != null)
OnButton1Click(this, null);
}
Within MyCustomControl class, define events that take (object sender, EventArgs e) and return void.
Then add (still within MyCustomControl) the event handlers for the click events of the internal buttons.
Inside these methods, do CustomClickEvent.Invoke().
Then, in the page containing your custom control, do myControl.CustomClickEvent += new CustomClickEvent(name_of_method_within_page);
To render an asp control from your Custom Control do that from Render base method:
protected override void Render(HtmlTextWriter writer)
Prepare before your controls with this method
protected override void CreateChildControls()

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

A confusion about webcontrol scope in 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;
...
}
}

How to do that fields not initialization?

how to do that every time s_Sort not update SortDirection.Desc
private SortDirection s_Sort = SortDirection.Desc;
protected void Page_Load(object sender, EventArgs e)
{
lblSort.Text = S_Sort.ToString();//every time == SortDirection.Desc - this is bad!
if (!IsPostBack)
{
ShowTree();
Validate();
}
}
Need
public void btnSortUp_Click(object sender, EventArgs e)
{
S_Sort = SortDirection.Asc;
}
public void btnSortDown_Click(object sender, EventArgs e)
{
S_Sort = SortDirection.Desc;
}
but after SortDirection.Desc is bad
The is a problem of the ASP.NET lifecycle. Every time a postback happens (for example, when btnSortUp or btnSortDown is clicked), a new instance of your page is created, i.e., S_Sort is reinitialized to Desc. If you want to persist the value between postbacks, you can store it in the viewstate, for example, by encapsulating it in a private property:
private SortDirection S_Sort {
get { return (SortDirection)(ViewState["S_Sort"] ?? SortDirection.Desc); }
set { ViewState["S_Sort"] = value; }
}

Resources