Reflecting Data in .NET Classes-Part III: From Windows Forms


Overview

This article is the 3rd in the 4 parts series Reflecting Data in .NET Classes. Mapping/Reflecting data from HTML forms and XML documents have been demonstrated in the first 2 parts. In this part, we will be looking at how to map/reflect data from a WinForm.

Description

This article assumes some basic understanding of Reflection, as it is what we rely the data mapping mechanism on. Some information about Reflection was covered in Part I - Reflecting data from HTML Forms (http://www.c-sharpcorner.com/UploadFile/tinlam/ReflectionInNetTLP111232005061511AM/ReflectionInNetTLP1.aspx
), while the Part II covers reflecting data from XML documents (http://www.c-sharpcorner.com/UploadFile/tinlam/ReflectingXMLData11262005003915AM/ReflectingXMLData.aspx). Now, lets see how we can reflect data from a WinForm. The data mapping logic with Reflection is the same as in Part I and Part II. A method will first find out all the properties an object has, then take the name of each property, and try to locate a control with the same name. Finally, it checks to see which type the property is, and parses the value from the control to that type, then assigns the parsed/typed value to the property.

In the code download, which contains the WinForm project we demonstrated here, there are 3 classes worth mentioning.

  1. employee.cs, which contains a few properties and an overridden ToString() method.
  2. WinFormData.cs, which contains the data mapping code with Reflection.
  3. Form1.cs, which contains a WinForm, some controls and a button.

The button in the WinForm triggers a click event, which fires the following method:

private void button1_Click(object sender, System.EventArgs e)
{
BusinessEntity.employee emp =
new BusinessEntity.employee();
DataReflector.WinFormData.fillProperties(emp,
this);
MessageBox.Show(emp.ToString());
}

The method first creates an object of Type BusinessEntity.employee whose class definition is in employee.cs. It then pass the object, and a reference to itself (the Form) to the static method DataReflector.WinFormData.fillProperties() whose class definition is in WinFormData.cs. The class properties will be filled with the data from the Form with just a single call to this method! Now, as an experiment, we can just simply call the ToString() method to get a string containing the values in the properties, and display it.



The current implementation of the DataReflector.WinFormData class only knows how to map data from ComboBox and TextBox. All other types of control are ignored. Which means you will need to put additional mapping logic to the class before you will see it maps other controls. But its just a matter of adding some more if-else statements etc. The underlying general control-property mapping, as well as parsing and converting the value to a specify type are already in place.

Up Next
    Ebook Download
    View all
    Learn
    View all