...Technology Simplified

Wednesday, February 29, 2012

Create Custom control in ASP.Net using C# from scratch

No comments :

Introduction

ASP.NET already contains a TextBox control to design web applications . You can develop your own custom control using the existing TextBox control by deriving it from the “TextBox” class from ASP.NET framework from scratch.

I selected System.Web.UI.WebControls.WebControl as the base class, because of the convenience and ease and we will also implement support for “postback” and “viewstate.” We will also examine client-side JavaScript!

The System.Web.UI.Control class has only a few rendering methods which could be overridden. This gives us less flexibility in developing the custom control, when we compare it with the rendering methods available in the System.Web.UI.WebControls.WebControl class. Of course, some of the most important properties (like width, height, font, and so on) of the WebControl class get inherited to our textbox control.

Before talking too much about the control, let us go to the implementation first. We will create a Visual Studio.NET 2010.

Developing the “MyTextBox” Control

Now, we will develop a simple “Textbox” type of control right from scratch. I call it “MyTextBox”.The following steps helps you to create the custom control using Visual Studio.NET 2010.

Click start -> Programs -> Microsoft Visual Studio .NET 2010 ->Microsoft Visual Studio .NET 2010 to open the IDE (Integrated Development Environment).

Steps to follow:

  • Click File -> New -> Project.
  • Within the “new project” dialog box select “Visual C# projects” as the project type, “Web Control Library” as the template and provide the name “SimpleCustomControl” along with the location you desire (Figure:1), and finally click “ok.”
    clip_image002[6]
  • Within the solution explorer, right-click on “ServerControl1.cs” and select “delete” to delete it.
  • Go to the project menu and select “Add New Item.”
  • Within the “Add New Item” dialog box select “CustomControl” and name it “MyTextBox.cs.”
  • Modify code (or just copy and paste) in the editor as follows:

namespace SimpleCustomControl

{

[DefaultProperty("Text"), ToolboxData("<{0}:MyTextBox runat=server></{0}:MyTextBox>")]

public partial class MyTextBox : WebControl,IPostBackDataHandler

{

public MyTextBox()

{

InitializeComponent();

}

public string Text

{

get { return ViewState["text"] + ""; }

set { ViewState["text"] = value; }

}

protected override void Render(System.Web.UI.HtmlTextWriter output)

{

base.AddAttributesToRender(output);

output.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID);

output.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);

output.AddAttribute(HtmlTextWriterAttribute.Type, "text");

output.AddAttribute(HtmlTextWriterAttribute.Value, Text);

output.RenderBeginTag(HtmlTextWriterTag.Input);

output.RenderEndTag();

}

public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)

{

if (Text != postCollection[this.UniqueID])

{

Text = postCollection[this.UniqueID];

return true;

}

return false;

}

public void RaisePostDataChangedEvent()

{

}

}

}

Press Shift+CtrI+B to build the solution

It results in error .

clip_image003[6]

Delete the dispose method and build again.

Testing the control with a Web Application

We need to test the created custom control using a web application. Now, we shall create a web application (within the same solution as above), refer to the previous web control, drag it onto the web page and finally test it. The following steps would guide you through the process.

  • Within the same solution, Go to File -> Add Project -> New Project
  • Select the project type as “ASP.NET Web Application” name it as ‘SimpleCustomControlTest’ .” Within the solution explorer, right-click on the web application , select the “Set as Startup Project”.
  • Within the solution explorer open the “SimpleCustomControlTest” project and select “References.” Right-click on “references” and select “Add Reference.”
  • Within the “Add Reference” dialog box, select “Projects” tab and click on “select” button and click “ok” as shown in the following figure (2).
    clip_image004[6]
  • Open the tool box, right-click on “General” tab and select “Choose Items.”
  • In the “Custom Toolbox” dialog box, click “browse” and go to the bin folder of the “SimpleCustomControl” project. Select the “SimpleCustomControl.dll” file, click “Open” and click “Ok.”
  • You should be able to see a new control within the “web forms” section of the tool box named “MyTextBox” (it generally gets added at the bottom).
  • Drag as many “MyTextBox”es as you want onto the “WebForm1.aspx” in design mode.
  • Drag two buttons and change the text as “Show” and “PostBack” respectively.

<cc1:MyTextBox ID="MyTextBox1" runat="server" />

<cc1:MyTextBox ID="MyTextBox2" runat="server" />

<asp:Button ID="Show" runat="server" Text="Show" onclick="Show_Click" />

<asp:Button ID="Postback" runat="server" Text="Postback" />

· Modify the “button1_click” event (of “Show” button) as follows:

protected void Show_Click(object sender, EventArgs e)

{

MyTextBox1.Text = "hello world";

}

  • Execute the solution, type some messages in all of the textboxes and try to “postback.” You can even click the “Show” button.

Understanding MyTextBox

In this section, we shall go into the details of the “MyTextBox” custom control. First of all let us consider the following line:

public partial class MyTextBox : WebControl,IPostBackDataHandler

Any custom control needs to be derived either from System.Web.UI.Control or System.Web.UI.WebControls.WebControl.But the use of “IPostBackDataHandler”? This is the interface we need to implement to support the feature of “postback.”

We define a property named “text,” which has the “viewstate” support.

public string Text

{

get { return ViewState["text"] + ""; }

set { ViewState["text"] = value; }

}

Any information we store in “viewstate” would exist to the server even after further web requests from the same page.

All of the information available in “viewstate” will be encoded and added to a hidden field to the same page by the ASP.NET runtime. When a post back occurs, all the information in that hidden field again gets posted to the server along with new pairs of values. We then check (or compare) the previous values (or information in viewstate) with recently modified values by the user and modify the view state accordingly during a “postback” event. This could be observed better from the next section.

Also we have:

protected override void Render(System.Web.UI.HtmlTextWriter output)

{

base.AddAttributesToRender(output);

output.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID);

output.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);

output.AddAttribute(HtmlTextWriterAttribute.Type, "text");

output.AddAttribute(HtmlTextWriterAttribute.Value, Text);

output.RenderBeginTag(HtmlTextWriterTag.Input);

output.RenderEndTag();

}

The above code fragment is at the heart of displaying the “textbox.” First of all, I add all the attributes of the “input” tag such as name, id, type, value, so on .. using the “output.AddAttribute” method. “UniqueID” and “ClientID” are automatically generated when a control has been dragged from the toolbox on to the web form.

“MyBase.AddAttributesToRender(output)” is the statement which is essential to make it available as the first statement. All of the default attributes, such as “style” (what we set at design time using the properties window) will be added using that simple statement. If you forget that statement, you will be left with a very plain textbox without having any of your design time properties set.

Handling the “PostBack” from “ViewState”

In general, any server control in ASP.NET maintains its “state” even after a “postback.” The “postback” could occur in several ways, including by just clicking a “submit” button. Within our control, I would like to maintain the same. As I am already maintaining the “state” information through “viewsate,” I need to refresh (or place) the latest value (or information) within my control before the page gets disposed. This could be solved by implementing the interface “IPostBackDataHandler.”

Let us consider the following code:

public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)

{

if (Text != postCollection[this.UniqueID])

{

Text = postCollection[this.UniqueID];

return true;

}

return false;

}

public void RaisePostDataChangedEvent()

{

}

We need to implement two methods, namely “LoadPostData” and “RaisePostDataChangedEvent.” Within the “LoadPostData,” I am comparing the value available in “viewstate” (“text” property) with the posted value (could be the same or modified value) to the server with an IF condition. If a user modifies the value, the posted value would be different and we will update the latest value back to the “viewstate” using the same “text” property.

When the posted values are different from our previous state values and, if we want raise any events (such as the “textchanged” event or others), we would return TRUE. This in turn executes the method “RaisePostDataChangedEvent” (currently I implemented nothing inside that, as there exist no events within my control). Returning “false” would not execute “RaisePostDataChangedEvent” at all.

How can we change look and feel of the textbox?

If I would like to have the background color of “MyTextBox” to be automatically changed to a color when it receives the user's focus (or cursor) and back to the color white after losing the focus. Is this not cute? Now we shall see how to implement this. Modify your “render” method, which looks like this:

protected override void Render(System.Web.UI.HtmlTextWriter output)

{

base.AddAttributesToRender(output);

output.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID);

output.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);

output.AddAttribute(HtmlTextWriterAttribute.Type, "text");

output.AddAttribute(HtmlTextWriterAttribute.Value, Text);

output.AddAttribute("onfocus", "event.srcElement.style.backgroundColor='beige';")

output.AddAttribute("onblur", "event.srcElement.style.backgroundColor='white';")

output.RenderBeginTag(HtmlTextWriterTag.Input);

output.RenderEndTag();

}

Within the Render method (above), we are just adding two more attributes to enable look and feel.

This control is just to show you the basic idea to create custom control from scratch.Hope it will help you proceed further with different implementations.

you can fins the sample code of this application here.

Good luck.

No comments :

Post a Comment