I have a pretty large webform that spans about 4 ajax TabPanel tabs.
Normally I just write the code to populate each control with the proper value I
pull using LINQ to SQL. But in my quest to learn more about c# I wondered if I
could loop through all the controls in the form and populate them abstractly
without having to say Control.Text = linqobject.field etc...
I was discussing this with a friend of mine who said he uses reflection to
accomplish this. Granted ne never writes asp.net apps, mostly classes and
libraries in VB.NET. To start off I named my controls with the corresponding column name from the database, for example my column name from the db is 'FirstName', so I would name my corresponding textbox 'txtFirstName'. I think this will make it easier to give relation to the control and its field in the db.
So I started studying reflection and understand WHAT it
does (exposes an object's types, methods, etc..), just not how it does it. I
started playing with it for about 3 hours last night and literally got no
where. My friend really tried to help but he's never worked with asp.net or c# before and was lost also. What he recommended is returning the record from linq into a collection or list, and then looping through all the controls in my form and setting the value property to the corresponding column name. I'm pulling my data in using the following LINQ query:
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()
where company.ContactID == cid
select new {company, plan, dental}).Single(); Now I HAVE to use the .Single() method to fill my company, plan, and dental objects because I'm still using controls that manually get filled by them. Like so:
txtCompanyName.Text = contact.company.CompanyName;
But when I use the .Single() method, it makes my contact object not IEnuermable anymore (right??), therefore I can't GetType().GetField() each contact object to return the fieldname. At this point I'm at a lost. I can vision what I want to do but have no idea how to get there. Something like:
foreach (Control c in Controls)
{
if (c.GetType() == typeof(TextBox))
{
c.Text = contact.dental.? //FieldName generated from c.ID
}
} How can I accomplish this? Sorry if the question is vague, I'm exhausted :) Thank you!