Clear Text Boxes on a Form in VB
Today’s tutorial is a rather simple but very effective trick that will improve the overall user experience. If you are building a site that is form intensive (let’s say an online instruction course website) and the user would like to clear text boxes that he has inputed because he is not happy with his answer. Instead of the user going through and deleting all of the answers himself, we will create a button and tie an event to it that will clear all Text Box fields for him. Let’s Begin
Create The Project
If you have not done so, create an empty web site. Open Visual Studio and click File > New > Web Site. Using ‘Visual Basic’ as the installed template, select ASP.NET Empty Web Site, name the file Page and click OK. Right click on the web site name and click Add New Item. Using ‘Visual Basic’ as the template, select Web Form, leave the file name as Default.aspx and click add.
Now that we have a web form to work on, we can start adding items from the toolbox to complete the process. Expand the toolbox panel and grab and place a Button item inside the open and closing div tags. Go ahead and add Three Textboxes as well as a Label Field to add some text. Your code should look something like this:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Type in something here"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Clear All" />
To add control and function to your button, simply switch to Split View and double click the Button. Visual Studio will pull up the Default.aspx.vb VB code page. An area is blocked off to input your code for the Button. Within the Sub code you will create a function that will replace the text (using .Text) to an empty string. Your code should look like this:
Partial Class _Default
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
Test the page on your web browser and voila! You have a clear all fields button.
Wrapping it Up
This tutorial is a very simple breakdown on how to tie an action to a button that will clear only a few fields. On a larger project, a more maintainable approach is required that would look for all TextBoxes within a given field and remove the character strings.