Link to home
Start Free TrialLog in
Avatar of DrPcKen
DrPcKen

asked on

Reflection setValue to match my controls to my datacontext fields.

I recently discovered reflection and realized how powerful it was to automate a lot of my mundane code writing.  For example I have a webform with over 300 fields.  I use a LINQ datacontext to manage the data, and instead of going through each control and say control = dataobject.field I thought I could use Reflection to match them together.

First I named my controls to have the same ID as my database fields, but I would put 'txt' or 'ddl' in front of them.  So my textbox would be 'txtFirstName' and my database field would be 'FirstName'.  When the page loads I would just say For each Control get the properties of my datacontext and match the ID's (removing the 'txt' from the beginning of the control name of course).  This works great.  Then I thought I could do the same thing with my updates and inserts, but I'm having a TON of problems with the setValue() method...

Looking at the code, I'm getting an error 'Object does not match target type'.  I'm not sure what I'm doing different.  Here's what I thought I would do:  pull all the properties for the datacontext object and loop through them matching them with the corresponding textbox (or control). See my code below.  I still get the error and I don't know why.

I've been trying to solve this for almost two days.
clientBenefitDataContext db = new clientBenefitDataContext();
 
        var contact = (from company in db.Contacts
                       from plan in
                           (
                               from p in db.PlanOptionsForContacts
                               where p.ContactID == company.ContactID
                               select p
                           ).DefaultIfEmpty()
                       from dental in
                           (
                               from d in db.DentalPlansForContacts
                               where d.ContactID == company.ContactID
                               select d
                           ).DefaultIfEmpty()
                       from vision in
                           (
                               from v in db.VisionPlansForContacts
                               where v.ContactID == company.ContactID
                               select v
                           ).DefaultIfEmpty()
                       where company.ContactID == Convert.ToInt32(cid)
                       select new { company, plan, dental, vision }).Single();
 
 
foreach (PropertyInfo field in contact.dental.GetType().GetProperties())
                {
                    
                    if (field.Name.ToString() == "id" || field.Name.ToString() == "ContactID")
                    {
                        continue;
                    }
                    else
                    {
                       
                        Type columnType = field.PropertyType.GetGenericArguments()[0];
                        if (columnType == typeof(DateTime))
                        {
 
                           TextBox txt = (TextBox)Globals.FindControlRecursive(ContactTabContainer, string.Format("txt{0}", field.Name.ToString()));
                                
                            field.SetValue(field.Name, rdp.Text, null);  // this is where the error is thrown
                            
                        }
                        //From here I want to set all the DataContext fields then do a db.SubmitChanges
                        
                    }
                    
                }

Open in new window

Avatar of DrPcKen
DrPcKen

ASKER


I think I just about got it using this code, but when I'm trying to get the type of the datacontext property (string, datetime, int32, etc...) it returns 'System.Runtime'.

DentalPlansForContact dp = new DentalPlansForContact();
                Type dbType = dp.GetType();

                foreach (PropertyInfo field in dbType.GetProperties())
                {

                    if (field.Name.ToString() == "id" || field.Name.ToString() == "ContactID")
                    {
                        continue;
                    }
                    else
                    {
                        Type columnType = field.Name.GetType(); //Trying to get TYPE here!
                        if (columnType == typeof(DateTime))
                        {

                            RadDatePicker rdp = (RadDatePicker)Globals.FindControlRecursive(ContactTabContainer, string.Format("txt{0}", field.Name.ToString()));

                            field.SetValue(dp, rdp.SelectedDate, null);
                            continue;

                        }
                        if (columnType == typeof(String))
                        {
                            TextBox txt = (TextBox)Globals.FindControlRecursive(ContactTabContainer, string.Format("txt{0}", field.Name.ToString()));

                            field.SetValue(dp, txt.Text, null);
                            continue;
                        }
                        if (columnType == typeof(Decimal))
                        {
                            TextBox txt = (TextBox)Globals.FindControlRecursive(ContactTabContainer, string.Format("txt{0}", field.Name.ToString()));

                            field.SetValue(dp, txt.Text, null);
                            continue;
                        }
                        if (columnType == typeof(Int32))
                        {
                            DropDownList ddl = (DropDownList)Globals.FindControlRecursive(ContactTabContainer, string.Format("ddl{0}", field.Name.ToString()));

                            field.SetValue(dp, Convert.ToInt32(ddl.SelectedValue), null);
                            continue;
                        }

                    }



                }
                db.SubmitChanges();
ASKER CERTIFIED SOLUTION
Avatar of Rudolf_Abel
Rudolf_Abel

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
field.SetValue(contact.dental, DateTime.Parse(rdp.Text), null);

OR
 
DateTime dt=DateTime.Now;
if(DateTime.TryParse(rdp.Text, out dt))
{
          field.SetValue(contact.dental, dt, null);
}
else
{
          //throw new Exception("Invalid date/time format");
}
Avatar of DrPcKen

ASKER

Great! That looks like that is setting the datacontext value properly.  Now I'm running into a similar problem I had last night.

When it loops through my foreach block, it gets the field type of the datacontext object like this:

Type columnType = field.PropertyType.GetGenericArguments()[0];

This of course gets the data type of the column in the datacontext object.  Now on my form my first control is a textbox with a datetime, my second is an int32, and my third is a string.   The foreach loops through my datetime and int32 just fine but when it gets to a string datatype and tries to get the type, I get this error on the GetGenericArguments()[0] method:

Index was outside the bounds of the array.

Why is it having a problem getting the string datatype but everything else seems fine?

Thanks for your help!
Avatar of DrPcKen

ASKER

Ok the problem I'm having now is whenever I try to get the type of my object and it is a string, it errors out saying 'Index was outside the bounds of the array'.  All the other datatypes don't have this problem.  

This is how I'm getting the datatype:

Type columnType = field.PropertyType.GetGenericArguments()[0];