Custom WebControl with OnClick event

  • Thread starter Thread starter Tomasz J
  • Start date Start date
T

Tomasz J

Hello Developers,

How do create a custom WebControl (not UserControl), exposing OnClick event?
I reviewed countless examples found by Google, but came across nothing
helpful.
Below I attach what I got so far.

Thank you for any hints.

Tomasz J


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

[DefaultProperty("Text")]
[ToolboxData("<{0}:MyButton runat=\"server\"></{0}:MyCloseButton>")]
public class MyButton : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(false)]
public string Text
{
get
{
String s = (String)ViewState["Text"];
return ((s == null) ? String.Empty : s);
}

set
{
ViewState["Text"] = value;
}
}

// should I use: Attributes.Add("OnClick",
Page.Clientscript.GetPostBackEventReference(this, ID.ToString))

[Category("New"), Browsable(true)]
public event EventHandler Click;

protected void OnClick(EventArgs e)
{
if (Click != null) {
Click(this, e);
}
}

protected override void RenderContents(HtmlTextWriter output)
{
output.WriteBeginTag("div");
output.WriteAttribute("style", "cursor:pointer;");
output.WriteAttribute("onclick", "alert('test');");
output.Write(HtmlTextWriter.TagRightChar);
output.Write(Text);
output.WriteEndTag("div");
}
}
 
Hallo TomaszJ
How do create a custom WebControl (not UserControl), exposing OnClick
event?
I reviewed countless examples found by Google, but came across nothing
helpful.
Any Control beside the Button itself uses clientside Javascript to do a
PostBack and raise Events.
If you want to create a Button like control that have all the
functionalities like CommandName and CommandArgument, you have to derive
from IButtonControl And IPostBackEventHandler, or directly from the button
class.
Otherwise, you have to handle the whole thing with Javascript.
The GetPostBackReference Methode gives you a return value, that you must bin
to a hyperlink target or an clientside eventhandler of an Html Control
(<Control>.Attributes.Add(<attribute>, <postback reference>)).

Such a control have to implement the IPostBackEventHandler interface to
raise the event.

A good example of an control that handle an event that raised by javascript
is the Link Button:
-
http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.linkbutton(VS.80).aspx

An example for an very, very basic button control as customcontrol can be
found here (only in german):
-
http://msdn2.microsoft.com/de-de/library/system.web.ui.ipostbackeventhandler(VS.80).aspx

The GetPostBackReferenceMethode can found in the Page.ClientScript class:
-
http://msdn2.microsoft.com/en-us/library/system.web.ui.page.clientscript(VS.80).aspx


HTH
 
Back
Top