A
A
Andrew2016-12-09 19:06:33
.NET
Andrew, 2016-12-09 19:06:33

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;
}

There is an attribute
[AttributeUsage(AttributeTargets.Field)]
    public class HideAttribute: Attribute
    {
        public int State { get; set; }

        public HideAttribute(int state)
        {
            State = state;
        }
    }

I'm trying to change the property of a field
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;
                }
            }
}

For some reason, in this method, at the very beginning, an empty array gets into managementsItems.
Why is that?
Thank you)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Nemiro, 2016-12-09
@byte916

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 question

Ask a Question

731 491 924 answers to any question