Today’s tutorial is a rather simple but very effective trick that will improve the overall user experience in your next C# project. 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 C# 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 C# 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:

Pretty straight forward so far. As you can see, the controls will code and set up all the appropriate assets as well as give our button the proper OnClick event.

C# code

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.cs C# code page. An area is blocked off to input your code for the Button. In order to have the button event clear all text fields, we must construct some logic by using the foreach and if conditional. We will tell the computer to do the following: “Look for each ‘Control’, if the type is ‘TextBox’, then replace the text with ’empty space’, if the text boxes have controls, then clear the text boxes. Your code should look like the example below.

Test the page in your browser and it should now clear all text fields.. You can add as many text fields as you like and the button will still clear all fields.

Wrapping it Up

With this code, you can scale your form intensive site to hold thousands of text boxes and have to ability to clear them all at once. This will make it easier to maintain for future projects as well to any future additions you may have to your site.