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!


About the Author

Vladimir Enchev

is Director of Engineering, Native Mobile UI & Frameworks

Comments