How To: Strongly typed values for your TextBoxes

by Vladimir Enchev | Comments 4

Very often you need to parse/convert TextBox Text property value to some other type however I’ve never seen any universal approach for this so far… and I’m offering you one :)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

public static class TextBoxExtensions
{
    public static T Value<T>(this TextBox textBox)
    {
        return (!String.IsNullOrEmpty(textBox.Text))? ChangeType<T>(textBox.Text) : default(T);
    }

    public static T ChangeType<T>(object value)
    {
        return (T)Convert.ChangeType(value, Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T));
    }
}


It's simple, isn't it? :) Example:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write(TextBox1.Value<Decimal?>());
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" Text="Button1" runat="server" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>


Enjoy!

,
Senior Technical Architect

4 Comments

Ben Hayat
Vlad, would this approach work for Silverlight too?
Thanks!
..Ben
Vlad
Hi Ben, Here is the Silverlight version: public static class TextBoxExtensions {     public static T Value<T>(this TextBox textBox)     {         return (!String.IsNullOrEmpty(textBox.Text)) ? ChangeType<T>(textBox.Text) : default(T);     }     public static T ChangeType<T>(object value)     {         return (T)Convert.ChangeType(value, Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T), CultureInfo.CurrentCulture);     } } Example: namespace SilverlightApplication1 {     public partial class Page : UserControl     {         public Page()         {             InitializeComponent();             Button1.Click += new RoutedEventHandler(Button1_Click);         }         void Button1_Click(object sender, RoutedEventArgs e)         {             decimal? value = TextBox1.Value<decimal?>();         }     } } Vlad

Comments

  1.    
      
      
       
  2. (optional, emails won't be shown on public pages)
  3. (optional)
Read more articles by Vladimir Enchev - or - read latest articles in Developer Tools