define Custom Event for WebControl in asp.net - c#

I need to define 3 events in a Custom Control as OnChange, OnSave, and OnDelete.
I have a GridView and work with its rows.
Can you help me and show me this code?

Good article which can help you to achieve your task:
Custom Controls in Visual C# .NET
Step 1: Create the event handler in your control as below.
public event SubmitClickedHandler SubmitClicked;
// Add a protected method called OnSubmitClicked().
// You may use this in child classes instead of adding
// event handlers.
protected virtual void OnSubmitClicked()
{
// If an event has no subscribers registered, it will
// evaluate to null. The test checks that the value is not
// null, ensuring that there are subscribers before
// calling the event itself.
if (SubmitClicked != null)
{
SubmitClicked(); // Notify Subscribers
}
}
// Handler for Submit Button. Do some validation before
// calling the event.
private void btnSubmit_Click(object sender, System.EventArgs e)
{
OnSubmitClicked();
}
Step 2 : Utilize the event in the page where you register your control. The following code is going to be part of your page where your control is registered. If you register it, it will be triggered by the submit button of the control.
// Handle the SubmitClicked Event
private void SubmitClicked()
{
MessageBox.Show(String.Format("Hello, {0}!",
submitButtonControl.UserName));
}

Related

Add event delegate to event handler of ASP.NET user control

I have a web user control in asp.net - a keypad. It has buttons for all digits, a textbox for display of input and clear and submit buttons. The user control sits in AJAX update panel so it can be easily shown/hidden. (App is destined for tablet browsers) I need to add a delegate to subMitButton ClickEventHandler inside my user control inside AJAX update panel. Any suggestions? Is it even possible? I don't want to use tablet's soft numeric keyboard because it is way to big. I could break my user control apart and use its code inside my web site but I'd rather use user control as intended.
you can raise an event from usercontrol which can be handled in the page .
You can declare a event
public event EventHandler SubmitButtonClick;
protected void OnSubmitButtonClick()
{
if (SubmitButtonClick!= null)
{
SubmitButtonClick(this, new EventArgs());
}
}
And then on the page, handle the event .
WebUserControl1.SubmitButtonClick+=
new WebUserControl.EventHandler(WebUserControl1_SubmitButtonClick);
private void WebUserControl1_SubmitButtonClick(object sender, EventArgs e)
{
Label1.Text = "Button Pressed";
}
Because of the ASP.NET webpage lifecycle I get Nulls when I set public properties on the user control from the main page. Those variables go out of scope once the page is sent to the client. However, here is an easy solution that will let you get notified when an event happens in your user control.
NOTE: There are some issues with Page.Context when back in the main page so changing things that effect the viewstate might not work.
Inside my user control i did the following...
// UC - setting up delegate and usercontrol property to store it
public delegate void CallbackAction(object sender, CustomEventArgs e);
public CallbackAction OnCallbackAction
{
get { return Session["CallbackAction"] as CallbackAction; }
set { Session["CallbackAction"] = value; }
}
Somewhere in the UserControl an event happens that you want to notify the main page of
// UC - callback from within the usercontrol
protected void UserControlButton_Click(object sender, EventArgs e)
{
if (IsPostback)
{
// do some processing
if (this.OnCallbackAction != null)
{
this.OnCallbackAction.Invoke(this, new CustomEventArgs("ET phone home") );
}
}
}
The structure above will now callback a main page that registers with the usercontrol. Here is how to register with the usercontrol from the main page
// Main Page - load event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback)
{
// register with usercontrol
this.UserControlFoo.OnCallbackAction += CallbackFromUserControl_Click;
}
}
// Main Page - this event will get called back when ET phones home
protected void CallbackFromUserControl_Click(object sender, CustomEventArgs e)
{
// phoned home from usercontrol
}

Why does my dynamically created user control doesn't fire button click event

i have a problem with user control.
i create it dynamically on my aspx page after clicking on a button:
protected void btnAddRules_Click(object sender, EventArgs e)
{
RuleProperty Control = (RuleProperty)LoadControl("RuleProperty.ascx");
MyPanel.Controls.Add(Control);
}
when i click on a button of my user control, the button event wont fire and the user control will disappear. here is the button event:
protected void btnAdd_Click1(object sender, EventArgs e)
{
WowzaRule rule = GetRuleFromGUI();
RuleList.Add(rule);
//Session["RuleList"] = RuleList;
//List<WowzaRule> test = new List<WowzaRule>();
SaveToXMLFiles(txtdbnum.Text, RuleList);
}
i understand that after pressing the button on mypage the usercontrol is released and if its not created on pag_init or page Load it wont stay, but i need to create it on my button click event and find a way for it not to disapper.
thanks in advance, Daniel
You might have to add an event handler that it can fire the click event and call your delegate
Control.Click += btnAdd_Click1;
Dynamically created controls, once added, have to be on a page on every page load in order to work correctly. What happens in your case:
RuleProperty is added after the button click
Page loads with this control
User clicks on the button within RuleProperty
Control is not added to the control tree during the page load (corresponding code is only in the button click handler, and that button was not clicked)
ASP.NET does not know which control triggered the event, so the event is not processed
To go around this issue you need to add you control on every page loading, for example using some flag stored in ViewState:
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["AddRuleProperty"] != null && (bool)ViewState["AddRuleProperty"])
{
AddRulePropertyControl();
}
}
protected void btnAddRules_Click(object sender, EventArgs e)
{
AddRulePropertyControl();
ViewState["AddRuleProperty"] = true;
}
private void AddRulePropertyControl()
{
RuleProperty Control = (RuleProperty)LoadControl("RuleProperty.ascx");
MyPanel.Controls.Add(Control);
}
Update.
If you want to remove the control from the page later on in the control's click handler, you need to remove corresponding ViewState key. This is not possible from the control directly, since property Page.ViewState is protected, and also this would have created an unwanted dependency.
What seems as the right way to do this is to subscribe to the very same event from the Page (you might need to make this event visible from the controller) and reset the key in there. Like this:
private void AddRulePropertyControl()
{
RuleProperty Control = (RuleProperty)LoadControl("RuleProperty.ascx");
Control.ButtonClick += RuleProperty_ButtonClick;
MyPanel.Controls.Add(Control);
}
private void RuleProperty_ButtonClick()
{
ViewState["AddRuleProperty"] = false;
}
Please note that event name here is not real, this is just a sketch of what can be done.

RaisePostBackEvent: raise custom or default postback event method based upon the user control that caused the postback

I have a ASP.NET page that contains both javascript and ASP.NET user controls. When a postback is executed, I use the RaisePostBackEvent method to determine which method should be called. That way, it's possible to trigger a postback via javascript. For example, I load a User Control via a postback that was triggered via javascript. However, the events of such a user control can't be raised via postback anymore, because the RaisePostBackEvent method is called, rather than de default postback behaviour. So how can I call the default postback behaviour on a user control, from within the RaisePostBackEvent method?
public void RaisePostBackEvent (string eventArgument) {
string eventTarget = Request ["__EVENTTARGET"];
if (eventTarget == UniqueID) {
eventArgument = Request ["__EVENTARGUMENT"];
Action action = JsonConvert.DeserializeObject<Action>(eventArgument);
if (action.name == "display") Display(action.argument);
else if (action.name == "edit") Edit(action.edit);
}
else {
// Control control = GetPostBackControl(this.Page);
// !!! Raise the postback event on the control.
}
}
You could put postback logic into a separate method:
void Button_Click(object sender, EventArgs e)
{
DoButtonLogic();
}
so you could call it also from RaisePostback:
...
else
{
DoButtonLogic();
}
I had this statement in the OnInit event method of the user control containing the javascript:
protected override void OnInit (EventArgs e) {
Page.RegisterRequiresRaiseEvent(this);
}
When this statement is removed, it works.

DataRow Delete without firing CurrentChanged Event

Well, I have the following problem:
I need to delete a row from a bindingsource without fireing the CurrentChanged event. Deletion is working without any problems. But it raises the CurrentChanged event instantly, which leads to my code matching to the CurrentChanged event is being executed. That leads to a problem.
Is there any way to achieve a similar effect like .Delete() without raising the event?
Deleting a row will always raise the event, if there are any subscribers.
If the event code is under your control, you could set a flag which you check in the BindingSource_CurrentChanged event handler:
private void DeleteRow()
{
this.justDeletedRow = true;
this.bindingSource.DeleteRow(...);
}
protected void BindingSource_CurrentChanged(object sender ...)
{
if (this.justDeletedRow)
{
this.justDeletedRow = false;
return;
}
// Process changes otherwise..
}
If the code isn't under your control - if you're binding to a component, say - then you can unbind the handler while performing the operation:
private void DeleteRow()
{
this.bindingSource.CurrentChanged -= this.component.BindingSource_CurrentChanged;
this.bindingSource.DeleteRow(...);
this.bindingSource.CurrentChanged += this.component.BindingSource_CurrentChanged;
}

Raising the Load event within a dynamic loaded web usercontrol

I need to load a web user control dynamically.
Looking at http://weblogs.asp.net/srkirkland/archive/2007/11/05/dynamically-render-a-web-user-control.aspx, it states that the page lifecycle events are not fired.
I thought I might be able to raise the events through reflection. I cannot figure how to fire the events, am I missing something?
Thanks
Podge
You can do something like this before calling RenderControl:
Page page = new Page();
page.Controls.Add(report);
In this case Init method will be called.
an answer given on that link of yours
The standard Load event should fire just fine. The standard ASP.Net control events are raised for usercontrols. If you are wanting to fire events inside your usercontrol from the parent page then you'll want to do something like this:
Inside your usercontrol create an event and wire it up. In this example I'll call it from Page_Load:
public event EventHandler TestEvent;
protected void Page_Load(object sender, EventArgs e)
{
if (this.TestEvent != null)
{
this.TestEvent(this, e);
}
}
Inside your parent page wire up the user controls TestEvent:
protected override void OnInit(EventArgs e)
{
MyUserControl uc = LoadControl("~/PathToUserControl.ascx");
uc.TestEvent += new EventHandler(MyUserControl_TestEvent);
}
protected void MyUserControl_TestEvent(object sender, EventArgs e)
{
//this code will execute when the usercontrol's Page_Load event is fired.
}
Hope that helps!!

Categories

Resources