tags:

views:

60

answers:

3

I was just wondering if there is any easier ways to assign values to html controls from an object or vice versa in asp.net. To do it manually is just painful

//assign value
txtFirstName.Text = person.FirstName;

//retrieve value
var p = new Person();
p.FirstName = txtFirstName.Text;

However to do it "pragmatically" is also kind of painful because it's got so many cases as you can see in this code, which is based on the ideas from this article.

if ((ctrl as TextBox) != null)
{
    var txt = ctrl as TextBox;
    if (p.PropertyType == typeof (string))
        txt.Text = p.GetValue(data, null).ToString();
    else if (p.PropertyType == typeof (decimal))
        txt.Text = p.GetValue(data, null).ToString();
}
else if ((ctrl as DropDownList) != null)
{
    var dropdown = ctrl as DropDownList;
    dropdown.SelectedValue = p.GetValue(data, null).ToString();
}

I couldn't find any other clever ways to automate this. Can some one point me a clever way of doing it because the form I am doing has literally more than 100 fields I just don't want code it manually.

Thanks!

A: 

We use mygenerationsoftware to generate the basic UI - DB mapping to avoid doing this manually and then where-ever some customization is required, we change the code manually.

Vikram
A: 

To retrieve data on postback you can go back to the Request object and just do

string[] _ArrayOfFields = new string[]{"FirstName"};

string _FirstNameValue = Request.Form[_ArrayOfFields[0]];

etc

You can then do something similar when setting values to your controls

((TextBox)Page.Controls[Page.FindControl(ArrayOfFields[0])]).Text = "New Value";

BarneyHDog
your method won't work with any html controls other than text box (i mean the assignment bit)
Jeffrey C
+1  A: 

Sounds like good old fashioned DataBinding might help?

Binding to Business Objects

ObjectDataSource example

Binding to Databases

codeulike