Is it possible to retrieve property names from a databound item?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-06 05:59:52

问题


I have this code-behind that checks each item in a repeater when it is databound to see if the author/date are empty (either no author/date, or the system is set to not display them) so that way I can clear out their respective labels. This is so I dont get something like "Posted By on" when there is not author and/or date specified.

Here is the code:

protected void Page_Load(object sender, EventArgs e)
{
    repeater.ItemDataBound += new RepeaterItemEventHandler(repeater_ItemDataBound);    
}

void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Literal PostedBy = (Literal)e.Item.FindControl("litPostedBy");
        Literal PostedOn = (Literal)e.Item.FindControl("litPostedOn");
        string Author = (string)DataBinder.Eval(e.Item.DataItem, "Author");
        string Date = (string)DataBinder.Eval(e.Item.DataItem, "PubDate");

        if (string.IsNullOrEmpty(Author))
        {
            if (string.IsNullOrEmpty(Date))
            {
                PostedBy.Text = "";
                PostedOn.Text = "";
            }
            else
            {
                PostedBy.Text = "Posted ";
            }

        }
    }
}

I am using a CMS, and I am unsure of what all the properties are in the e.Item.DataItem. Is there some way I can loop through the DataItem and print out the property names/values?

Thanks!


回答1:


What properties DataItem will have depends on what kind of object it contains. It will contain the object from the data source that is currently being processed when databinding the repeater. The following method takes any object and lists the properties it contains:

private static void PrintAllProperties(object obj)
{
    obj.GetType().
        GetProperties().
        ToList().
        ForEach(p => 
            Console.WriteLine("{0} [{1}]", p.Name, p.PropertyType.ToString()
            ));
}

Example output (for a String instance):

Chars [System.Char]
Length [System.Int32]


来源:https://stackoverflow.com/questions/1131424/is-it-possible-to-retrieve-property-names-from-a-databound-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!