create custom server or user button

223 views Asked by At

I have a very specific problem. I have a user control (code below) That needs to act like a button. I have researched into writting a custom server control but I think that is kind've over kill. The other option i have come accross is having the div tag fire a javascript onclick and that would trigger an asp:button click event. But I also feel that is also hacky.

The solution I am looking for is that whenever the user control is clicked it will fire a onClick event (acting like a normal button, except with my desired markup).

(user control code) there is css styling for the font, that shouldn't impact the issue.

  <div style="border:2px solid black; background-color:white" >
    <div>
      <asp:Label ID="lblMeetingCityState" runat="server" Text='<%# Eval("City") %>'></asp:Label>
    </div>
    <div>
      <asp:Label ID="lblMeetingDate" runat="server" Text='<%# Eval("MeetingDate") %>'></asp:Label>
    </div>
    <div>
      <asp:Label ID="lblMeetingSite" runat='server' Text='<%# Eval("Location") %>'></asp:Label>
    </div>
  </div>

code behind to raise event on click

<System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
Partial Public Class MeetingButton
  Inherits System.Web.UI.UserControl
  Implements System.Web.UI.IPostBackEventHandler

  Public Event Click As EventHandler

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

  End Sub

  Protected Overridable Sub OnClick(ByVal E As EventArgs)
    RaiseEvent Click(Me, E)
  End Sub

  Public Sub RaisePostBackEvent(ByVal eventArgument As String) _
         Implements IPostBackEventHandler.RaisePostBackEvent

    OnClick(New EventArgs())
  End Sub
End Class
3

There are 3 answers

0
gh9 On BEST ANSWER

An asp:linkbutton seems to do what I need.

4
bleepzter On

IPostBackEventHandler Interface will allow you to do this. Basically in the code behind of your user control add the following:

public class MyUserControl: Control, IPostBackEventHandler {

      // Defines the Click event.
      public event EventHandler Click;

      //Invoke delegates registered with the Click event.
      protected virtual void OnClick(EventArgs e) {

         if (Click != null) {
            Click(this, e);
         }   
      }


      // Define the method of IPostBackEventHandler that raises change events.
      public void RaisePostBackEvent(string eventArgument){

         OnClick(new EventArgs());
      }

}
0
Daveloper On

In your usercontrol codebehind, use the ClientScriptManager.GetPostBackEventReference method.