Web Development

ASP.NET basics: Working with the TextBox control

Developers often overlook basic programming options in favor of new or cool ways to deliver results. A good example is the ASP.NET TextBox Web control, which offers plenty of options for building applications.

Developers often overlook basic programming options in favor of new or cool ways to deliver results. This is true for many of the standard ASP.NET features. A good example is the TextBox Web control, which offers plenty of options for building applications. This week, I take a closer look at the TextBox control.

Used everywhere

It is hard to find an ASP.NET Web application that does not use a TextBox control. The venerable HTML input and textarea elements provide alternatives, but they include fewer features and ASP.NET integration.

The basic premise of the TextBox control is accepting user input. This may be as simple as a user entering a username or typing a multiline paragraph. The control provides plenty of methods and properties to work with it via code.

Programmatic control

Programmatic access is provided by the TextBox class located in the System.Web.UI.WebControls namespace. TextBox appearance and behavior may be manipulated via its properties. The following list provides a sampling of the properties:

  • AutoPostBack: Boolean value signaling whether the AutoPostBack feature is enabled for the control. This determines if the form will automatically be posted back to the Web server when the contents of the field change.
  • BackColor: The background color of the control. This may be controlled with CSS as well.
  • BorderColor: The border color for the border (if used) displayed around the control.
  • BorderWidth: The width of the border around the control on the page.
  • CausesValidation: Boolean value signaling whether validation is performed when postback of form is executed.
  • Columns: The display width of the TextBox control.
  • CssClass: Allows you to assign a CSS class to the control.
  • Font: The various font attributes associated with the control. The preferred approach is to use CSS, but the Font class contains properties for signaling whether the text appears in bold, italic, strikeout, or underline, as well as font size, name, and more.
  • ForeColor: The color of the text displayed in the field. The preferred technique is CSS.
  • Height: Get or set the height of the control.
  • MaxLength: The maximum number of characters allowed in the field.
  • ReadOnly: Boolean value signaling whether control may be edited by user or just read only.
  • Rows: The number of rows for a TextBox using the multiple line setting.
  • SkinId: Allows you to assign a skin to the TextBox to control its appearance.
  • Text: The text contained within the field.
  • TextMode: The text mode of the control. The legal values are found in the TextBoxMode class with values of single-line, multiline, or password. The password setting masks the text entered, so the password is not displayed -- it is available in the code for manipulation and storage.
  • Visible: Boolean value signaling whether the control is visible or hidden.
  • Wrap: Boolean value signaling whether text wraps within the field.

The following C# example demonstrates the properties used during a page load. The containing page for the code contains one TextBox control named TextBox1. The code sets the TextBox to multiline and setsfont properties and colors:

protected void Page_Load(object sender, EventArgs e) {

TextBox1.AutoPostBack = true;

TextBox1.BackColor = System.Drawing.Color.LightBlue;

TextBox1.BorderWidth = 4;

TextBox1.Columns = 80;

TextBox1.Font.Bold = true;

TextBox1.Font.Italic = false;

TextBox1.Font.Size = FontUnit.Larger;

TextBox1.ForeColor = System.Drawing.Color.Black;

TextBox1.Rows = 40;

TextBox1.TextMode = TextBoxMode.MultiLine;

TextBox1.Wrap = true;

TextBox1.Visible = true;

TextBox1.Text = "This is a test.";

}

The equivalent VB code follows:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

TextBox1.AutoPostBack = True

TextBox1.BackColor = System.Drawing.Color.LightBlue

TextBox1.BorderWidth = 4

TextBox1.Columns = 80

TextBox1.Font.Bold = True

TextBox1.Font.Italic = False

TextBox1.Font.Size = FontUnit.Larger

TextBox1.ForeColor = System.Drawing.Color.Black

TextBox1.Rows = 40

TextBox1.TextMode = TextBoxMode.MultiLine

TextBox1.Wrap = True

TextBox1.Visible = True

TextBox1.Text = "This is a test."

End Sub

The ASP.NET source is another option for working with the properties of the TextBox control. The following example mimics the functionality of the previous code snippet by using attributes of the <asp:Textbox> element.

<asp:TextBox

ID="TextBox1"

runat="server"

Height="117px"

Width="389px"

OnTextChanged="TextBox1_TextChanged"

AutoPostBack="true"

BackColor="lightblue"

Font-Bold="true"

Font-Italic="false"

BorderWidth="4"

Font-Size="Larger"

Columns="80"

TextMode="MultiLine"

Wrap="true"

Visible="true">

</asp:TextBox>

In the previous listing, you'll notice the OnTextChanged attribute, which allows you to respond to text changing within the control. The OnTextChanged attribute points to the method that will handle the change event.

The OnTextChanged event fires when the text in the control changes, and the control loses focus. Focus is lost when a user clicks outside of the TextBox control or tabs out of it.

The following snippet shows the TextBox1_TextChanged method tied to the OnTextChanged event in the previous listing. It displays the contents of the TextBox control at the top of the page via the Response object.

protected void TextBox1_TextChanged(object sender, EventArgs e) {

Response.Write(TextBox1.Text);

}

The next example uses the TextChanged event to trigger validation of the page. The page contains a RequiredFieldValidator control that is tied to the TextBox control, so it is required. The TextChanged code triggers validation if the field is empty; otherwise, it moves along. The ASP.NET page is listed first.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Start.aspx.cs" Inherits="WebApplication1.Start" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Working with TextBox control</title>

</head><body>

<form id="frmTextBoxTest" runat="server">

<asp:TextBox ID="TextBox1" Height="117px" Width="389px" runat="server" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

<asp:RequiredFieldValidator

ID="RequiredFieldValidator1"

runat="server"

ControlToValidate="TextBox1"

ErrorMessage="Please enter text">

</asp:RequiredFieldValidator>

</form></body></html>

The C# codebehind for the page follows:

public partial class Start : System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e) {

TextBox1.AutoPostBack = true;

TextBox1.BackColor = System.Drawing.Color.LightBlue;

TextBox1.BorderWidth = 4;

TextBox1.Columns = 80;

TextBox1.Font.Bold = true;

TextBox1.Font.Italic = false;

TextBox1.Font.Size = FontUnit.Larger;

TextBox1.ForeColor = System.Drawing.Color.Black;

TextBox1.Rows = 40;

TextBox1.TextMode = TextBoxMode.MultiLine;

TextBox1.Wrap = true;

TextBox1.Visible = true;

}

protected void TextBox1_TextChanged(object sender, EventArgs e) {

if (TextBox1.Text.Length > 0)

TextBox1.CausesValidation = true;

else

TextBox1.CausesValidation = false;

}

The previous snippet could be coded without the validation control, but it provides a simple example of using the CausesValidation property. Also, you could go a step further by using AJAX to avoid a full page postback to improve performance.

As previously stated, you should use CSS to control the presentation characteristics of the TextBox control. For example, the following ASP.NET page source creates a CSS class to format the TextBox as previously demonstrated with the properties of the TextBox class. The code uses the CssClass property of the TextBox control.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Start.aspx.cs" Inherits="WebApplication1.Start" %>

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

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>TextBox control styled with CSS</title>

<style media="all" type="text/css">

.textbox {

background: lightblue;

color: Black;

font-size: larger;

height: 117px;

width: 389px;

font-weight: bold;

border: 4;

}

</style>

</head>

<body>

<form id="frmTextBoxCSS" runat="server">

<asp:TextBox ID="TextBox1" CssClass="textbox" runat="server" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

</form></body></html>

Valuable feature

The TextBox control is a valuable piece of the ASP.NET system. It allows you to easily accept and work with user input -- simple or multiline text. Like most of its features, ASP.NET places plenty of options in the hands of the developer to control TextBox appearance and behavior. Additionally, you can extend the TextBox class to create a custom control.

Tell the Visual Studio Developer community about your experiences of working with the TextBox control. What other standard controls do use regularly?

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

---------------------------------------------------------------------------------------

Get weekly develoment tips in your inbox TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically subscribe today!

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

19 comments
nsesar
nsesar

Hello, I'm a newbie so thanks very much for the article. What would be the best way to change the height property of the TextBox based on contents (which is bound to a database and can be anywhere from 2 to 2000 characters)? I'm using ASP.NET web form and all intranet visitors are using IE. The control properties are set to multi-line wrap and width 100%. Any sample code would be greatly appreciated (VB preferred) .

morningz
morningz

The TextBox control has only been around what now, 6 years? How about some articles on Ajax or jQuery or SilverLight or anything that is at least "current" And a big deal is made in the article about "AutoPostBack" on a textbox control... what a useless property that is... what user would not be confused by the page kicking off a full blown page postback when they tab/click off the field?

motohead400
motohead400

Was it really necessary to write an article on the textbox? If you can't figure this out on your own you shouldn't be developing.

johnh
johnh

This is the 2nd article I've read today that is killing my workstation performance. I can see you've got all kinds of code on the page. Please stop inserting this garbage, or I know I'll be getting my info elsewhere.

JCharavda
JCharavda

Do you have a source.zip that we can download?

yaoliu68
yaoliu68

Come on, Tony, let's write something meanful.

BALTHOR
BALTHOR

They're probably that Geek Nerd stuff too.

Marshwiggle
Marshwiggle

Read "Thanks," above. Maybe if you can't take part in a formum without denigrating the work of others you shouldn't be posting. Try a little "egoless programming." It's good for the soul.

demozi
demozi

What shit piece of prehistoric machine do you have,man??? Still running DOS in a 386?? Get a life....if you are not happy, get your info elsewhere, as you said....

Justin James
Justin James

John - I am 99% sure that it is not our codeI am positive it is one of the Flash advertisements. When one of those Dice ads come up (the "Should I bother getting mainframe experience?" one for sure, and I beleive a few others), one of my cores sits at 100% usage. Could you please do me a favor and try to track this too? Unless I can get a few other people to show that they have this problem too (especially if it happens in different OS's or browsers), I cannot get any traction on this. I have passed it along before but it went nowhere, but if I have a few readers mentioning too, I bet someone will pay attention. Thanks! J.Ja

aspatton
aspatton

The level of experience of the readers varies - there are many that are new to the platform, so I try to mix the simple with the more complex. Please let me know any topics you would like to see covered in future columns.

Justin James
Justin James

That really was not a nice thing to say to him. Especially since he may be experiencing the same thing I do, which is that a few of the ads do something weird, and spike CPU usage on the core they are running on to 100%. If he's having that problem like I am, it is not his fault or his PC's fault at all. J.Ja

.Sherwood
.Sherwood

Tony, I am a more experienced developer, but I also appreciate that you cover the basics. Many if not most of us have been learning .Net programming on the job, and so there are holes in our knowledge and experience. You column is occassionally helpful in filling in those holes. We all learn in different ways; I learn best by example and usage. Thanks for putting in the effort to share your knowledge.

aspatton
aspatton

No apologies necessary, feedback is always appreciated.

yaoliu68
yaoliu68

Tony, I don't know what I was saying. Please keep up with the good works. Yes, I do remember that I learned a lot of basics from your posts in the past. In the future I'd like to see more SilverLight and WCF topics

aspatton
aspatton

Nobody can know everything, so most of us are learning as we go to a certain extent. Don't hesitate to let me know of any topics you'd like to see covered.

Justin James
Justin James

Sometimes by reading about (or trying to write about) the basics, I learn a lot. As someone who is self-taught (not even books, usually), it is quite surprising where the gaps in my knowledge are. For example, a few days ago I was reading about writing compilers in C#. Wow, pretty advanced topic! But that same day I blurred the lines between a namespace and an assembly so bad, it took me half the day to figure out what I was doing wrong. Sure, this stuff is basic Tony, but please keep it coming! J.Ja

Editor's Picks