I'm feeling like I'm missing something very important from my past experiences, however, here it is:
I am designing an end-user report designer using DevExpress for clients within my corporation. Since these are being generated dynamically, I would like to give clients the opportunity to have free range over what they are putting on the report. Instead of hard-coding all of the available values, I'm using a StartsWith
and a Substring
to retrieve the name of the control. I would like to use this string value to specify which parameter field they would need. I'm not sure if I'm thinking about this correctly or if I'm way off track, hoping someone can take another look and give me some suggestions.
Any information will be appreciated.
Maybe I need a dictionary or some sort of interface? Code snippet of what I currently have is below:
private static void BuildReportHeader(Notice notice, XRControl control)
{
if (control.Name.StartsWith("lbl"))
{
string elementName = control.Name.Substring(3);
XRLabel label = (XRLabel)control;
label.Text = notice.{elementName};
}
}
Obviously, this doesn't work or compile as it currently sits, just looking for a solution to the {elementName} bit so that I can access any field on that specific parameter.
CodePudding user response:
You can use reflection to perform this dynamic value lookup: notice.{elementName}
.
The bellow sample codes assumed that elementName
exist and it's public
.
If elementName is a property
var propertyValue = typeof(Notice).GetProperty(elementName).GetValue(notice);
- Please bear in mind that
GetValue
returns anobject
- The above code assumed that the
elementName
property has a getter- If it does not have then you will receive an
ArgumentException
- If it does not have then you will receive an
If elementName is a field
var propertyValue = typeof(Notice).GetField(elementName).GetValue(notice);
- The above code assumed that the
elementName
points to a field- If you provide a non-existing field name or a property/method name then you would receive a
NullReferenceException
becauseGetField
would returnnull
- If you provide a non-existing field name or a property/method name then you would receive a