Object Reference .NET

ref this.Object

Select Text or Value From DropDownList Extension Method

clock April 25, 2008 17:22 by author Dan
Here is a cool way to select an item from the DropDownList using it's value.

ddlCountries.Items.FindByValue(value).Selected = true;

However I keep forgetting how to do it and end up spending ages searching for it, so here is a very usefull extension method that allows you to select an item from a DropDownList using the text or value of the item without needing to know the index of the item.

using System;
using System.Runtime.Serialization;
using System.Web.UI.WebControls;
 
namespace Core.ExtensionMethods
{
    public class GenericDropDownListException : Exception, ISerializable
    {
        public GenericDropDownListException(string type, string value) : 
            base(string.Format("Unable to set  \"{0}\" to {1}", type, value)) { }
    }
 
    public static class DropDownListExt
    {
        public static void SelectValue(this DropDownList bob, string value)
        {
            try
            {
                if (bob.SelectedIndex >= 0)
                    bob.Items[bob.SelectedIndex].Selected = false;
                bob.Items.FindByValue(value).Selected = true;
            }
            catch
            {
                throw new GenericDropDownListException("value", value);
            }
        }
 
        public static void SelectText(this DropDownList bob, string text)
        {
            try
            {
                if (bob.SelectedIndex >= 0)
                    bob.Items[bob.SelectedIndex].Selected = false;
                bob.Items.FindByText(text).Selected = true;
            }
            catch
            {
                throw new GenericDropDownListException("value", text);
            }
        }
    }
}

Now all you need to do to select an item from the DropDownList is:

ddlCountries.SelectText("UK");

kick it on DotNetKicks.com


Enum TryParse Extension Method

clock April 21, 2008 14:43 by author Magz
TryParse method is very helpful if you need to convert string representation of a value to a value itself. TryParse is better than Parse method because it doesn’t throw any exceptions and just returns a Boolean value to indicate weather the parsing was successful. Surprisingly there is no TryParse method available to use for Enum and this is where extension method can be extremely useful.

public static bool TryParse<T>(this Enum theEnum, string valueToParse, out T returnValue)
{
    returnValue = default(T);
    int intEnumValue;
    if (Int32.TryParse(valueToParse, out intEnumValue))
    {
        if (Enum.IsDefined(typeof(T), intEnumValue))
        {
            returnValue = (T)(object)intEnumValue;
            return true;
        }
    }
    return false;
}

Now it’s time to test our extension method! Here I have a simple UserType Enumeration
public enum UserType
{
    None = 0,
    Administrator = 1,
    Manager = 2,
    Consultant = 3
}

I want to parse QueryString parameter usertype and store the result in currentUserType variable.

currentUserType.TryParse(Request.QueryString["usertype"], out currentUserType);

if Request.QueryString["usertype"] is invalid UserType then currentUserType variable will be set to None (0).

kick it on DotNetKicks.com 


To Extension Method

clock April 4, 2008 22:35 by author Naz
Many times you find yourself having to convert the type of an object to another. The ToString() method is probably one of the most useful methods, it's great for easy conversion of objects to string, but what if you want to do it the other way round or even an int to a decimal?

Say I had a string and I wanted it to turn it into an Int32, I could just use the Convert class and do a Convert.ToInt32(myInt) but I would like to be able to do this myInt.ToInt32().

Well now you can with .NET 3.5 Extension Methods! Here's my implementation

public static T To<T>(this IConvertible s)
{
    return (T)Convert.ChangeType(s, typeof(T));
}

All objects that inherit from an IConvertible e.g. string, int, bool etc., will convert the value to the type you specify e.g.

int myInt = myInt.To<Int32>();

It works perfectly with the Visual Studio Intellisense 


kick it on DotNetKicks.com 



RecentComments

Comment RSS

Sign in