将DataTable绑定到ASP.NET中的Repeater控件

时间:2015-02-17 07:28:56

标签: c# asp.net datatable

BusinessLogic.EventType:

namespace BusinessLogic
{
    public class EventType : IModel
    {
        public int EventTypeID;
        public string Name;
        public string Description;
        public string Photo;
    }
}

我的Aspx:

<asp:Repeater ID="rptr" runat="server">
            <ItemTemplate>
                <div class="col-lg-4 col-md-4 col-sm-4 mb">
                    <a href="#">
                        <div style="background-image: url('<%# Eval("Photo") %>'); height: 300px; display: block; background-size: cover; background-repeat: no-repeat; z-index: 1; left: 0; right: 0">
                        </div>
                        <div style="text-align: center; font-family: 'Comic Sans MS'; font-size: 20px; color: #db2828">
                            <%# DataBinder.Eval(Container.DataItem, "Name") %>
                        </div>
                </div>
                </a>
            </ItemTemplate>
        </asp:Repeater>

代码背后:

public partial class PastOrders : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["vendor"] != null)
        {
            if (!IsPostBack)
            {
                List<EventType> lstEventType = new List<EventType>();
                EventTypeLogic eventTypeLogic = new EventTypeLogic();
                DataTable dt = eventTypeLogic.SelectAll();

                lstEventType  = (from rw in dt.AsEnumerable()
               select new EventType()
               {
                   Name= Convert.ToString(rw["Name"]),
                   Photo = Convert.ToString(rw["Photo"])

               }).ToList();

                rptr.DataSource = lstEventType;
                rptr.DataBind();
            }
        }
        else
        {
            Response.Redirect("VendorLogin.aspx");
        }
    }
}

现在我使用了其中一个答案中提供的代码。编译好。但是会产生一个运行时错误:System.Web.HttpException: DataBinding: 'BusinessLogic.EventType' does not contain a property with the name 'Photo'.

我的tblEventType有以下列:EventTypeIDNameDescriptionPhoto

我不知道出了什么问题!

3 个答案:

答案 0 :(得分:1)

我假设您拥有EventType课程,如下所示

 public class EventType
 {
    public string Name{get;set;}
    public string Value {get;set;}
    ... more properties 
 }

并且您希望将数据库值添加到事件类型中,希望您创建EventType类的对象列表

你可以这样做

  lstEventType  = (from rw in dt.AsEnumerable()
               select new EventType()
               {
                   Name= Convert.ToString(rw["Name"]),
                   Value= Convert.ToString(rw["Value"]),
                   ... more properties 
               }).ToList();

答案 1 :(得分:0)

使用Named Arguments

这样的东西
 for (int i = 0; i < dt.Rows.Count; i++)
{
lstEventType.Add(new EventType(){
EventType=dt.Rows[i]["Name"].ToString()

});
}

答案 2 :(得分:-1)

for (int i = 0; i < DataTable dt.Rows.Count; i++)
{
  lstEventType.Add(dt.Rows[i]["Yourcolumn"].ToString());
 }