Wednesday, March 14, 2012

.NET/ASP.NET interview Questions - how to do Render and PreRender?

PreRender: -PreRender is an event which is used for modifying server controls just before sending them to the client. Render: -Render is an method which actually puts the HTML output to the response stream. Lets see an simple example to get an better idea, below is the code snippet for the same. To use PreRender event, we have to override it and can make necessary changes to the controls we want to. protected override void OnPreRender(EventArgs e) { foreach (GridViewRow row in GridView1.Rows) { row.ForeColor = Color.Blue; } } In the above code snippet, I have override the PreRender event and just changed the forecolor of the GridView. Now lets see how we can code for Render. Below is the code snippet for the same, in which I have override the Render and using “HtmlTextWriter” just displayed a simple HTML text output. protected override void Render(HtmlTextWriter writer) { writer.Write("This displays the grid in blue color"); base.Render(writer); } Below is the full code snippet so that you can try it by yourself and see the respective result. using System.Drawing; using System.Collections; namespace Data { public class Customer { public string CustomerCode { set; get; } public string CustomerName { set; get; } } public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { LoadGrid(); } public void LoadGrid() { ArrayList objArray = new ArrayList(); Customer ObjCustomer = new Customer(); ObjCustomer.CustomerCode = "1001"; ObjCustomer.CustomerName = "shiv"; objArray.Add(ObjCustomer); ObjCustomer = new Customer(); ObjCustomer.CustomerCode = "1002"; ObjCustomer.CustomerName = "Feroz"; objArray.Add(ObjCustomer); GridView1.DataSource = objArray; GridView1.DataBind(); } protected override void OnPreRender(EventArgs e) { foreach (GridViewRow row in GridView1.Rows) { row.ForeColor = Color.Blue; } } protected override void Render(HtmlTextWriter writer) { writer.Write("This displays the grid in blue color"); base.Render(writer); } } } In the above code snippet, I have used prerender event to change the forecolor of the girdview before the gridview is displayed on the client browser and I have override the render method to display the html output to the response stream. PreRender event executed before the render method gets called which creates the HTML code using the HtmlWriter.so in other words prerender event fires first and do the necessary changes to the server control and later the render method is called.

No comments:

Post a Comment

Could not find a part of the path ... bin\roslyn\csc.exe

I am trying to run an ASP.NET MVC (model-view-controller) project retrieved from TFS (Team Foundation Server) source control. I have added a...