AddAttribute


R

rn5a

Assume that a custom server control derived from
System.Web.UI.WebControls.WebControl encapsulates a Button & a TextBox.
The Button & the TextBox controls are added using the
CreateChildControls sub like this:

Namespace MyNS
Public Class MyClass : Inherits WebControl
Protected Overrides Sub CreateChildControls()
MyBase.CreateChildControls()
Dim txt1 As TextBox
Dim btn1 As Button

txt1 = New TextBox
btn1 = New Button

Me.Controls.Add(New LiteralControl("<br>"))

txt1.ID = "txt1"
txt1.EnableViewState = True
Me.Controls.Add(txt1)
btn1.ID = "btn1"
btn1.Text = "CLICK ME"
Me.Controls.Add(btn1)

ChildControlsCreated = True
End Sub
End Class
End Namespace

Now I want to add a OnClick event to the Button control which should
invoke a JavaScript function. This is what I tried:

Protected Overrides Sub AddAttributesToRender(ByVal Output As
HtmlTextWriter)
MyBase.AddAttributesToRender(Output)
Output.AddAttribute(HtmlTextWriterAttribute.OnClick, "CallSub1()")
End Sub

When I had a look at the HTML source of the ASPX page which uses the
above custom control, I found that the HTML source corresponding to the
AddAttributesToRender sub was:

<span id="sc1" onclick="CallSub1()"><br>
<input name="txt1" type="text" id="txt1" />
<input type="submit" name="btn1" value="CLICK ME" id="btn1" />
</span>

The OnClick event got associated with the <span> element rather than
with the Button. As a result, the JavaScript function gets invoked not
only when the Button is clicked but also when the TextBox is clicked.

How do I add the OnClick event ONLY to the Button so that the
JavaScript function gets invoked when the Button is clicked? Nothing
should happen if a user clicks any part of the TextBox (of course,
other than setting the focus on the TextBox).
 
Ad

Advertisements

B

bruce barker \(sqlwork.com\)

if you inherit frm webcontrol, then you are a span. attributes will be
applied to the span. to add a clcient click t the button, add the onclick
attribute to the button.

bt1.Attributes.Add("onclick","doclick();");

-- bruce (sqlwork.com)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top