As mentioned in the previous article, Orm is popular and there areCodeGenerator. Do I have to write code on the front-end? Today, let's talk about the class that uses the reflection mechanism to automatically bind the data persistence layer!
Protected Override Void Onitemdatabound (repeateritemeventargs E)
{
Foreach (Control VaR In E. Item. Controls)
{
Type TT = E. Item. dataitem. GetType ();
System. reflection. propertyinfo _ proinfo = TT. getproperty (var. ID );
If (_ Proinfo ! = Null )
{
Text = _ Proinfo. getvalue (E. Item. dataitem, Null ) = Null ? String . Empty: _ proinfo. getvalue (E. Item. dataitem, Null ). Tostring ();
}
}
}
In fact, the core of this Code is to first determine the type of the bound object class. Then, the Control ID is used to find the property with the same name in the corresponding object class and obtain its value.
In fact, this is too simple to write. But here is a tip. If a person ID is displayed in most projects, it is automatically converted to a person name and a page is displayed when you click the mouse. At this time, you can write an interface to achieve code reuse.
Public InterfaceIcustomitem
{
ObjectDataitem {Get;Set;}
}
Then add
If(VARIsIcustomitem)
{
(VARAsIcustomitem). dataitem=E. Item. dataitem;
}
If you implement this interface in a specific project, the repeater will automatically bind and display data as required.
By the way: in fact, girdview can also implement automatic binding, but I always think that girdview is too large to be used as a Web Front-end. So I like the lightweight repeater.