Thursday, August 14, 2008

Use extension Methods to Add new Functionality to ASP.Net Server Controls

i'm sure that most of you know enough about extension methods and for those who don't ,
extension methods are used to new methods to an existing type without any effort to modify the original type.

let's now start to see how we can use extension methods to add new functionality to ASP.Net Server Control.

example (1)

-with DropDownList

here is the original way of adding new Items to DropDownList


DropDownList1.Items.Add(new ListItem("mona"));

or

ListItem li = new ListItem("mona");
DropDownList1.Items.Add(li);


actually if you are going to Add only one item it's ok but what if you are going to add an array of items sure you are going to repeat the previous lines of code many times, let's now try to use an extension method to help us

step(1)
Create a static Class called ControlsUtil

public static class ControlsUtil
{

public static void AddToDDList(this DropDownList ddl, string values, bool IncludeEmpty)
{
string [] splitter;
if (IncludeEmpty)
splitter = values.Split(new char[] { ',' }, StringSplitOptions.None);
else
splitter = values.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int Count = 0;
while (Count <>


step(2)

Create a web Page and add a DropDownList

step(3)
Switch to Code Behind and write the following Code

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.AddToDDList(" ,A,B,C,D,E,F,G,H", true);
}
}


step(4)
run you page and see the result






- with WebPage

in many web pages there might be a lot of Textboxs that you may need to clear after clicking certain button sure you can Create your own method that clear all the Textboxs but you still need to repeat this method in every page, now let's use extension methods to help us.

step (1)

Open the Static class that we created before and add the following method


public static void ClearTextBoxs(this object obj,IEnumerable e)
{
foreach (object o in e)
{
TextBox txt = o as TextBox;
if (txt != null)
txt.Text = string.Empty;
}
}


step (2)

Create your web page that contains any number of Textboxs and a button



step (3)

now switch to code behind of the Button Click event and add the following code

protected void Button1_Click(object sender, EventArgs e)
{
this.ClearTextBoxs(form1.Controls);
}


step (4)

run your page ,add text to the TextBoxs



step (5)

then Click the Button and see the result


Note: this method can also be used with UserContols not just webPages

3 comments:

Mohammed Nour said...

Very nice hint. I have just see yesterday similar use for it for MVC controls - esp. MVC HTML Helpers:

Building Custom ASP.NET MVC Controls

Jones said...

nice blog...
visit also asp.net example

mona said...

hey Jones, you have a nice blog too :)