Thursday, March 8, 2007

ASP.Net Custom Server Control Lessons

When writing a custom server control in ASP.Net it is pretty straight forward. It is common to put the output of the control right in the Render() method. Be aware this is very late in the control and page lifecycle. What that means if you try to modify the value of another control on the page it will appear to work in code, but the changes will not be shown in the browser. The reason is that the page is being rendered, it is too late to change .net server control values. So, it is easy to do put the "render" code in OnLoad(). Here is an example.

protected override void OnLoad(EventArgs e) { // do "rendering here" if you need to change values on the page i.e. raising an event ControlOutput = "<span>Hi</span>"; } protected override void Render(HtmlTextWriter output) { output.Write(ControlOutput); }

If you want to reproduce something link a LinkButton you will need to implement IPostBackEventHandler. This works in conjunction with __doPostBack() method.

Page.ClientScript.GetPostBackEventReference(this, "MyActionNameHere"). To learn more about this, check out the ASP.Net QuickStart

1 comment:

electronic signature software said...

I was facing the same scenario that if I try to modify the value of another control on the page it will appear to work in code, but the changes will not be shown in the browser. I was unable to guess the actual reason that you mentioned.Its really informative.