无法将数据表值分配给类列表

时间:2014-08-26 11:40:16

标签: asp.net-mvc-4

这是我的模特:

public class Category
    {
        public Category()
        {
            SubCategory = new List<SubCategory>();
            TicketsInfo = new List<TicketInfo>();
            UserDetails = new List<UserDetails>();
        }

        [Key]
        public int CategoryId { get; set; }
        public string Name { get; set; }


        public List<SubCategory> SubCategory { get; set; } //subcategory is my another class
        public List<TicketInfo> TicketsInfo { get; set; }//ticketinfo is my another class
        public List<UserDetails> UserDetails { get; set; }//userdetails is my another class
    }

这是我的控制者:

DataTable categoryDetailsforTickets = categoriesBal.FetchTicketDetailsforSubcategory(categoryId);
            List<Category> categoryModelforTickets = new List<Category>();

            if (categoryDetailsforTickets.Rows.Count != 0)
            {
                for (int i = 0; i < categoryDetailsforTickets.Rows.Count; i++)
                {
                    Category categoryModel = new Category();
                    categoryModel.TicketsInfo[i].TicketId =(int) categoryDetailsforTickets.Rows[i].ItemArray[i];
                    categoryModel.UserDetails[i].FName = categoryDetailsforTickets.Rows[i].ItemArray[i].ToString();
                    categoryModel.TicketsInfo[i].Subject = categoryDetailsforTickets.Rows[i].ItemArray[i].ToString();
                    categoryModelforTickets.Add(categoryModel);
                }
            }

但它在这一行上引发了我的错误:

categoryModel.TicketsInfo[i].TicketId =(int) categoryDetailsforTickets.Rows[i].ItemArray[i];

指数超出范围。必须是非负数且小于集合的大小。 参数名称:index

我的数据表中有两条记录。

任何人都可以找出问题是什么???

1 个答案:

答案 0 :(得分:0)

您还必须在此处指定列:

 categoryModel.TicketsInfo[i].TicketId =(int)categoryDetailsforTickets.Rows[i][0];   

OR

categoryModel.TicketsInfo[i].TicketId =(int)categoryDetailsforTickets.Rows[i]["coloumnname"];

OR

尝试将数据表迭代为: -

foreach (DataRow row in categoryDetailsforTickets.Rows) // Loop over the rows.
{
  categoryModel.TicketsInfo[i].TicketId =(int)row["coloumnname"];
  ........
}