Answer the question
In order to leave comments, you need to log in
How to manage the state of the fields of an object through attributes?
C# is used, the project is webforms, the task is to control the visibility of the web-control through attributes.
If it’s easier, you need to access the property of the object and change the property of this property :)
Here is a class with a field
public partial class Doc1 : BaseDoc{
[Hide(1)]
protected DateEdit tbe_DateTo;
}
[AttributeUsage(AttributeTargets.Field)]
public class HideAttribute: Attribute
{
public int State { get; set; }
public HideAttribute(int state)
{
State = state;
}
}
public abstract class BaseDoc{
public void DoFieldManagement()
{
var managementsItems = GetType().GetMembers().Where(m => Attribute.IsDefined(m, typeof(HideAttribute))).ToList();
foreach (var item in managementsItems)
{
WebControl control = new WebControl(HtmlTextWriterTag.A);
if (item is FieldInfo)
{
control = (WebControl)((FieldInfo)item).GetValue(typeof(WebControl));
}
var hideAttr = (HideAttribute)item.GetCustomAttributes(typeof(HideAttribute), true).First();
if (hideAttr.State== 1)
{
control.Visible = false;
}
}
}
Answer the question
In order to leave comments, you need to log in
Use BindingFlags :
var managementsItems = this.GetType().GetMembers
(
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public
).Where(m => Attribute.IsDefined(m, typeof(HideAttribute))).ToList();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question