Here's a scenario that I ran into frequently when I was working in web forms. Let's say that you have form with some controls on it. Now let's say that you need to reset that form based on some user action or an event. Let's assume this is the markup of your aspx page. <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %> Now inside your reset method you could go over each textbox one at a time and reset the text, like this, but I don't like that approach. protected void btnReset_OnClick(object sender, EventArgs e) First I think it takes too much repetitive typing and second you have to modify the method if you add another textbox. Now if you look closely there is another problem with this approach. I missed that zip code textbox. It is pretty easy to miss a single textbox. Now imagine if your page also had other controls like checkboxes or radio button groups. You can see that the reset method would quickly grow to be a large method. Let's see if we can find a better way. What I did was to create a static helper class and inside that class create a static method that will return all of the children controls of a given type. Here is the code for the helper class. public static List<T> GetControls<T>(Control root) Now you can change your reset method to simply call the helper method. In addition you don't have to change your reset method every time you add a new textbox. Let's see the GetControls<T> method in action. protected void btnReset_OnClick(object sender, EventArgs e) Much better. You don't have to worry about forgetting a control or changing your reset every time you change your aspx page. In this example I'm pointing the GetControls method at the root Page. You could just as easily point it at another control, like a table or a div, if you only wanted to clear a subset of the controls. Hope that is helpful for you and as always, Happy Coding.
|
AuthorWelcome to The Blind Squirrel (because even a blind squirrel occasionally finds a nut). I'm a full-stack web and mobile developer that writes about tips and tricks that I've learned in Swift, C#, Azure, F# and more. Archives
April 2018
Categories
All
|