Click here to Skip to main content
Click here to Skip to main content

How to Get and Set Values of Input Control Types Using Iteration

, 30 Nov 2006
Rate this:
Please Sign up or sign in to vote.
An article on using iteration to get and set the values of various input contol types.

Sample Image

Introduction

Ever have a user input form that has a lot of input fields that you need to set or get the values from a data source? Typically, programmers would programmatically get and set each individual field in their server side code. This article describes a method to capture all of the input controls and then iterate through the controls to either get or set the values. The goal of this article is to provide the programmer with a more efficient way of getting and setting control values when dealing with a large input form.

Background

Recently, I was involved in a project which required users to fill out an online form that contained over 40 input fields. Some of the field values needed to be pre-populated from a data source and others were for the user to complete. Traditionally, I would have programmatically set and get the field values line by line, control by control. Because this was just one of 10 such forms, it would have taken a large amount of time to program this task. Furthermore, every time the client requested me to add a new form, I would have to go through the lengthy process again and again. But we would like to be smarter than this so that we can focus more on solving business problems and not just be code monkeys!

The ControlFunctions Class

The ControlFunctions class contains the methods to get and set the value of any input type control. An input type control could be a TextBox, DropDownList, ListBox, CheckBox, CheckBoxList, RadioButton, or RadioButtonList. Basically, any form control object that a user can use to input information.

The ControlFunctions class uses a pseudo-factory method to enable a programmer to pass any control to the class. The pseudo-factory then figures out what type of control it is and then the class knows how to properly set the value of that control.

For example, to set or get the value of a TextBox control, you might do something like this:

string MyValue = MyTextBox.Text;
MyTextBox.Text = (string)MyValue;

However, to set or get the value of a CheckBox control, you might do something like this:

bool MyValue = MyCheckBox.Checked;
MyCheckBox.Checked = (bool)MyValue;

The ControlFunctions class handles for you the getting and setting of a control no matter what input type control it is.

SetControlValue Method

The SetControlValue method sets the values for each input type control in the collection. Recursion is used here to make sure that we get all child controls as well:

public void SetControlValue(ControlCollection controlCollection, ArrayList values) 
{ 
    foreach (Control control in controlCollection) 
    { 
        foreach (ControlItem controlItem in values) 
        { 
            if (control.ID == controlItem.ID) 
                SetControlValue(control, controlItem.Value); 
        }
        // Recursion 
        if (control.HasControls()) 
            SetControlValue(control.Controls, values); 
    } 
}

The SetControlValue method also has an overload method for setting an individual control value. This is also an example where we implement a pseudo-factory:

public void SetControlValue(Control control, string value)
{
    Type _ctlType = control.GetType();
    switch (_ctlType.Name)
    {
        case "TextBox":
            SetTextBox(control, value);
            break;
        case "DropDownList":
            SetDropDownList(control, value);
            break;
        case "ListBox":
            SetListBox(control, value);
            break;
        case "CheckBox":
            SetCheckBox(control, value);
            break;
        case "CheckBoxList":
            SetCheckBoxList(control, value);
            break;
        case "RadioButton":
            SetRadioButton(control, value);
            break;
        case "RadioButtonList":
            SetRadioButtonList(control, value);
            break;
        default:
            break;
    }
}

The Set<Control Type> Methods

Once the factory has figured out what type of input control it is, the Set<Control Type> method then knows how to deal with that particular control:

private void SetTextBox(Control control, string value)
{
    TextBox _ctl = (TextBox)control;
    _ctl.Text = value;
}

private void SetDropDownList(Control control, string value)
{
    DropDownList _ctl = (DropDownList)control;
    _ctl.SelectedIndex = _ctl.Items.IndexOf(_ctl.Items.FindByValue(value));
}

private void SetListBox(Control control, string value)
{
    ListBox _ctl = (ListBox)control;
    ArrayList values = StringToArrayList(value);

    foreach (ListItem li in _ctl.Items)
    {
        if (values.Contains(li.Value))
            li.Selected = true;
        else
            li.Selected = false;
    }
}

private void SetCheckBox(Control control, string value)
{
    CheckBox _ctl = (CheckBox)control;
    _ctl.Checked = Convert.ToBoolean(value);
}

private void SetCheckBoxList(Control control, string value)
{
    CheckBoxList _ctl = (CheckBoxList)control;
    ArrayList values = StringToArrayList(value);

    foreach (ListItem li in _ctl.Items)
    {
        if (values.Contains(li.Value))
            li.Selected = true;
        else
            li.Selected = false;
    }
}

private void SetRadioButton(Control control, string value)
{
    RadioButton _ctl = (RadioButton)control;
    _ctl.Checked = Convert.ToBoolean(value);
}

private void SetRadioButtonList(Control control, string value)
{
    RadioButtonList _ctl = (RadioButtonList)control;
    ArrayList values = StringToArrayList(value);

    // There is no enumerator for the RadioButtonList class so
    // the RadioButtonList needs to iterate by index
    for (int i = 0; i < _ctl.Items.Count; i++)
    {
        ListItem li = _ctl.Items[i];

        if (values.Contains(li.Value))
            li.Selected = true;
        else
            li.Selected = false;
    }
}

Supporting Methods

The following methods are used to convert ArrayLists and Strings that are used by the above methods:

private ArrayList StringToArrayList(string value)
{
    ArrayList _al = new ArrayList();
    string[] _s = value.Split(new char[] { ',' });

    foreach (string item in _s)
        _al.Add(item);

    return _al;
}

private string ArrayListToString(ArrayList value)
{
    StringBuilder _s = new StringBuilder();
    int _count = 0;

    foreach (string item in value)
    {
        _s.Append(item);

        if (_count < value.Count - 1)
            _s.Append(",");

        _count++;
    }

    return _s.ToString();
}

The ControlItem class

The ControlItem class contains the properties for getting and setting the values of a collection:

using System;

namespace i3.Common.Utilities
{
    public partial class ControlItem
    {
        private string m_ID;
        public virtual string ID
        {
            get { return m_ID; }
            set { m_ID = value; }
        }

        private string m_Value;
        public virtual string Value
        {
            get { return m_Value; }
            set { m_Value = value; }
        }

        public ControlItem()
        {
        }

        public ControlItem(string id, string value)
        {
            m_ID = id;
            m_Value = value;
        }
    }
}

The Default.aspx.cs Code-Behind

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using i3.Common.Utilities;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }

    private void SetControlValues()
    {
        // Create the ControlFunctions object
        ControlFunctions _cf = new ControlFunctions();

        // Iterate through the page controls
        foreach (Control c in this.Controls)
        {
            Type _ctlType = c.GetType();

            // Only get the controls that are contained inside of the form
            if (_ctlType == typeof(HtmlForm))
            {
                // Pass the controls to the ControlFunctions object to do the work
                _cf.SetControlValue(c.Controls, MyData());
                break;
            }
        }
    }

    private ArrayList MyData()
    {

        // Prgrammatic method to create data.
        // Data could be from any data source that
        // can then be loaded into an arraylist.
        // Notice that the ID of the data item matches the ID of the control.
        ArrayList _al = new ArrayList();
        _al.Add(new i3.Common.Utilities.ControlItem("Item1", "Roger Waters"));
        _al.Add(new i3.Common.Utilities.ControlItem("Item2", "3"));
        _al.Add(new i3.Common.Utilities.ControlItem("Item3", "2,3"));
        _al.Add(new i3.Common.Utilities.ControlItem("Item4", "true"));
        _al.Add(new i3.Common.Utilities.ControlItem("Item5", "1,3"));
        _al.Add(new i3.Common.Utilities.ControlItem("Item6", "true"));
        _al.Add(new i3.Common.Utilities.ControlItem("Item7", "3"));

        return _al;
    }

    private ArrayList GetControlValues()
    {
        ArrayList _al = new ArrayList();

        // Create the ControlFunctions object
        ControlFunctions _cf = new ControlFunctions();

        // Iterate through the page controls
        foreach (Control c in this.Controls)
        {
            Type _ctlType = c.GetType();

            // Only get the controls that are contained inside of the form
            if (_ctlType == typeof(HtmlForm))
            {
                // Pass the controls to the ControlFunctions object to do the work
                _al = _cf.GetControlValue(c.Controls);
                break;
            }
        }

        return _al;
    }

    private void BindGridView()
    {
        GridView1.DataSource = GetControlValues();
        GridView1.DataBind();
    }

    protected void btnSet_Click(object sender, EventArgs e)
    {
        SetControlValues();
    }

    protected void btnGet_Click(object sender, EventArgs e)
    {
        BindGridView();
    }
}

Points of Interest

The sample code also provides the Get methods for getting the values out of the control and are similar to the Set methods. It only deals with controls that would be considered input type controls. This class could be extended to work with pretty much any type of control you would want to get or set the value of (labels, lists, etc.). You will notice in the sample code the IDs of the controls are the same as the IDs of the ArrayList of data that I am working with. A programmer could easily develop a field mapping class that will map the column name to the control ID and thus provide a more loosely coupled design. For simplicity in this article, I do not provide an example of this. Also, I used the type string for passing the value of the control around. A programmer will have to go through another process of converting this string value properly when sending the data to a data source. I could have used the object type and created another factory to determine the data type and perform the proper conversion. Again, for simplicity in this article, I do not provide an example of this.

When coding for this project, I also discovered an anomaly with the RadioButtonList control. When working with this control programmatically, I found that there is no enumerator for the RadioButtonList object as expected. Hence, I had to reference the ListItem by index.

Hopefully, you will find this class useful as I have.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Michael Crandall
Web Developer
United States United States
Michael Crandall is a C# and VB.NET developer. His experience encompasses single applications up to enterprise level multi-tier applications. You can learn more by visiting his site at http://www.mjcrandall.com

Comments and Discussions

 
QuestionControlItem Pinmembereeweex4-Aug-10 12:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 30 Nov 2006
Article Copyright 2006 by Michael Crandall
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid