Using Extention methods in ASP.net 3.0 and 3.5 with generics.

 Rate It (1)

Since the Dawn of asp.net web based developement has become hell lot of easy. It has provided a great control over, design and code. and lets developer to emphasis more over his/her Business logic rather then messing their head with the roughness of historical style of working on web development using old scripting languages.

And with the time MS has tried to improve it and change in the way of wev development. The best thing i like about MS technologies it is highly reusable and flexible. So now without wasting anymore time i will directly jump on the main topic, i.e. using extention methods in asp.net

I assume that most of the readers have hear about extention methods atleast of 1 time. But still I am trying to put a brief description about extention methods.

"Extention methods are very cleverly designed tool to create more sensefull and resuable code for any perticular scenario which is repeatable in various situations and scenarios.  These are static classes which contains one or many static methods which can be directly injected in to the required object for a defined purpose"

I will not edxplain why and how it is resuable, Although i will demostrate a example which will explain my defination of Extention methods.

Just take an example that you have a multi select list box, where you select multiple items from it. this is the best you can do with any listbox. but each time you will do this, to find selected items you have to loop through all the items of listbox. It may be condition that you need selected item array in some defined datatypes. such as string, int, float, double, datetime etc.
Now you can say i can use generics for that why should I use extention methods. So the answer is as follows. in todays IT development time line is always limited and the workload keeps on increasing, as Project managers always says, "This can be done in 5 mins!", but they never tell HOW?. Now in such a situation a developer works like a BULL, day in day out, and most of the time we all redundent our code and put some patch work just to finish the target. But we never think that the more and more code we write the more time it take to manage it.

Ok enough talking. Now getting out of my project manager's delima here is an simple example of Extention method using generics.

So here I am trying to create a method which will give me all the selected items of any listbox in an array in the datatype format I want.

So first create one listbox with some string values, or copy from below

<asp:ListBox ID="ListBox1" runat="server" Height="70px" Width="177px" SelectionMode="Multiple" >
        <asp:ListItem>India</asp:ListItem>
        <asp:ListItem>Australia</asp:ListItem>
        <asp:ListItem>Spain</asp:ListItem>
        <asp:ListItem>Denmark</asp:ListItem>
        <asp:ListItem>Egypt</asp:ListItem>
        <asp:ListItem>Qatar</asp:ListItem>
        <asp:ListItem>Nepal</asp:ListItem>
        <asp:ListItem>China</asp:ListItem>
        <asp:ListItem>Brazil</asp:ListItem>
    </asp:ListBox>

As you can see i have a List box whose ID is ListBox1 where selection mode is multiple.
so on the run time i can select more then one country or all, and my requirment is to get all the selected items should come in string array.

now create one class or in the  code behind of this aspx copy and paste code given below under the same namespace.
////////////////////////////
public static class ControlExtentions
    {
        // Using ListBox Class to inject this method in ListBox Class
        // Using <T> for getting resultant array iin desired format
 public static T[] ToListArray<T>(this ListBox control) where T : IConvertible
        {
            // Create List Array Object Of type <T> in local variable newList type var
            var newList = new List<T>();
     // Now loop through all the items of this Listbox
            foreach (ListItem li in control.Items)
            {
               // check every item if it is selected

               if (li.Selected)
                {
  `   // If selected then change the type of currently selected item's Text in to type T and
         aad it into newList.
                    newList.Add((T)Convert.ChangeType(li.Text, typeof(T)));
               
                }

            }
     // finally return then List into Arrat Format
            return newList.ToArray();
        }

    }
}
//////////////////////////

It is fairly easy and simple to understand how above method will work, well you can also go through the code comment.
Now how to use this.
As i have use this class under same name space to demonstrate the logic we don't have to add any namespace fore this, but it is strongly advised that you use method in seperate class so the scope of this method will be increased. and then you just have to use this name space in your code behind.

Ok Ya, i was talking about how we will use this.
now create one button on your aspx and on it's postback event try to use the code provided below.

string[] selectedCountries= ListBox1.ToListArray<string>();

you will find that not only your Listbox control knows that who is ToListArray<T>() method is, it also knwo that when you will call this method what output it will provide.

Now to test furthur more.. add another Listbox and populate it with Datetime,
now then only thing you have to change in your code is this

DateTime[] selectedCountries= ListBox1.ToListArray<DateTime>();

Now test it again.
So the conclusion is, that using this new feature of .net we can reduce the effort of rewardless coding and can actually write few usefully code that will be more versatile and reusable.
I hope you guys those who are new to extention methods will able to write more better and reusable codes.
NOTE: If you write anything good , do share with us.
Cheers for now :)

 

Revision number 1, Wednesday, April 30, 2008 8:11:47 PM by
This is not the most up to date version of this article. The most recent version can be found here.

Comments

Very interesting. Thanks a lot

LINQ is your friend! public static T[] ToListArrayT>(this ListBox control, FuncListItem, T> selector) { return control.Items.CastListItem>() .Where(li => li.Selected) .Select(selector) .ToArray(); } public static T[] ToListArrayT>(this ListBox control) where T : IConvertible { return control.ToListArrayT>( li => (T)Convert.ChangeType(li.Text, typeof(T)) ); }

thank u

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. mbanavige (5)
  2. SGWellens (4)
  3. maartenba (2)
  4. rami_nassar (2)
  5. stiansol (2)
  6. MisterFantastic (2)
  7. satish1.v (1)
  8. raklos (1)
  9. mosessaur (1)
  10. Jos Branders (1)

Advertise Here

Microsoft Communities
Page view counter