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" "">

<script runat="server">

    protected void Button1_Click(object sender, EventArgs e)

<html xmlns="">
<head runat="server">
    <title>Untitled Page</title>
    <form id="form1" runat="server">
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" Text="Button1" runat="server" OnClick="Button1_Click" />


About the Author

Vladimir Enchev

is Director of Engineering, Native Mobile UI & Frameworks


Comments are disabled in preview mode.