0

Say I want to use the TextChanged event on a TextBox. Why does the event show up in the aspx file as "OnTextChanged"?

 <asp:TextBox ID="Textbox1" runat="server" 
    OnTextChanged="Textbox1_TextChanged"></asp:TextBox>

Coming from both a WPF and WinForms background, this seems odd to me. I am used to seeing event names referred to in the same manner. What is happening in the background to change "OnTextChanged" to just "TextChanged".

Nate
  • 5,237
  • 7
  • 42
  • 52

2 Answers2

2

TextChanged is an event OnTextChanged is a handling delegate. You cannot assign to an event. Instead of it you AddHandler in vb code but you assign a value to OnTextChanged attribute in declarative syntax. I think that difference is in direction event is from an object but the method reference is assigned to some property. So On prefix is to emphasize difference.

The class has

Public Event TextChanged As EventHandler

and

Protected Overridable Sub OnTextChanged (e As EventArgs )

is the method raising rising an event. There is similar logic.

IvanH
  • 5,039
  • 14
  • 60
  • 81
  • That's interesting. So based on the example at http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.ontextchanged.aspx you use OnTextChanged to raise the TextChanged event. Why would you also use in in the aspx file to add a handler to the TextChanged. Weird. – Nate May 09 '13 at 19:34
2

I'm pretty sure it's just a convention. Seems like the events don't start with On but the overridable function does.

Public Event TextChanged(sender As Object, e As System.EventArgs)

vs

Protected Overridable Sub OnTextChanged(e As System.EventArgs)
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
the_lotus
  • 12,668
  • 3
  • 36
  • 53
  • I see that it is a convention (which is good to know), I just want to understand what is happening to cause the OnTextChanged method (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.ontextchanged.aspx) to add a handler (TextBox1_TextChanged) to the TextChanged event. The OnTextChanged documentation makes it sound like the method is used for raising the event (with and example overriding the default behavior). – Nate May 09 '13 at 19:46
  • 1
    @Nate maybe this could help: http://stackoverflow.com/a/1006968/130611 – the_lotus May 09 '13 at 19:52