In today's project, the control is obtained based on the control name. After finding relevant information, the implementation method is as follows. This code is C # and can be converted to VB.net.
// The namespace system. Reflection, system. componentmodel must be referenced.
/// <Summary>
/// Set the value based on the control name and attribute name
/// </Summary>
/// <Param name = "classinstance"> instance where the control is located </param>
/// <Param name = "controlname"> Control name </param>
/// <Param name = "propertyname"> attribute name </param>
/// <Returns> attribute value </returns>
Public static object getvaluecontrolproperty (Object classinstance, string controlname, string propertyname)
{
Object result = NULL;
Type mytype = classinstance. GetType ();
Fieldinfo myfieldinfo = mytype. getfield (controlname, bindingflags. nonpublic | // "|" is an OR operation. Unless both bits are 0, the operation result is 0, and the other operations result is 1.
Bindingflags. instance );
If (myfieldinfo! = NULL)
{
Propertydescriptorcollection properties = typedescriptor. getproperties (myfieldinfo. fieldtype );
Propertydescriptor myproperty = properties. Find (propertyname, false );
If (myproperty! = NULL)
{
Object CTR;
CTR = myfieldinfo. getvalue (classinstance );
Try
{
Result = myproperty. getvalue (CTR );
}
Catch (exception ex)
{
MessageBox. Show (ex. Message );
}
}
}
Return result;
}
/// <Summary>
/// Assign values based on the control name and attribute name
/// </Summary>
/// <Param name = "classinstance"> instance where the control is located </param>
/// <Param name = "controlname"> Control name </param>
/// <Param name = "propertyname"> attribute name </param>
/// <Param name = "value"> attribute value </param>
/// <Returns> attribute value </returns>
Public static object setvaluecontrolproperty (Object classinstance, string controlname, string propertyname, object value)
{
Object result = NULL;
Type mytype = classinstance. GetType ();
Fieldinfo myfieldinfo = mytype. getfield (controlname, bindingflags. nonpublic
| Bindingflags. instance );
If (myfieldinfo! = NULL)
{
Propertydescriptorcollection properties = typedescriptor. getproperties (myfieldinfo. fieldtype );
Propertydescriptor myproperty = properties. Find (propertyname, false); // set this parameter to true to avoid case sensitivity.
If (myproperty! = NULL)
{
Object CTR;
CTR = myfieldinfo. getvalue (classinstance); // obtain the control instance
Try
{
Myproperty. setvalue (CTR, value );
Result = CTR;
}
Catch (exception ex)
{
MessageBox. Show (ex. Message );
}
}
}
Return result;
}
// Call
// Label1.text = textbox1.text, label2.text = textbox2
// Private void button#click (system. Object sender, system. eventargs E)
//{
// Int I;
//
// For (I = 1; I <= 2; I ++)
//{
// This. setvaluecontrolproperty (this, "label" + I. tostring (), "text", getvaluecontrolproperty (this, "textbox" + I. tostring (), "text "));
//}
//}