是否可以从数据绑定项中检索属性名称?

时间:2009-07-15 13:31:04

标签: c# data-binding repeater

我有这个代码隐藏,当它被数据绑定时检查转发器中的每个项目,看看作者/日期是否为空(没有作者/日期,或者系统设置为不显示它们)这样我可以清除各自的标签。如果没有指定作者和/或日期,我就不会得到像“发布者”这样的内容。

以下是代码:

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

        }
    }
}

我使用的是CMS,我不确定e.Item.DataItem中的所有属性是什么。有什么方法可以遍历DataItem并打印出属性名称/值吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

DataItem将具有哪些属性取决于它包含的对象类型。当数据绑定转发器时,它将包含当前正在处理的数据源中的对象。以下方法接受任何对象并列出它包含的属性:

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

示例输出(对于String实例):

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