如何在网格视图中添加选中的项?

时间:2015-05-20 12:11:23

标签: c# asp.net entity-framework

List<ListItem> checkedItemList = subjectCheckBoxList.Items.Cast<ListItem>()
                                     .Where(c => c.Selected).ToList();

subjectGridView.DataSource = checkedItemList;  // causes exception
subjectGridView.DataBind();

我想在列表视图中查看具有主题ID和名称的所选项目。网格视图的项目是Model.Student类型。我的代码给出了一个例外。我该怎么办?

2 个答案:

答案 0 :(得分:0)

对于GridView数据源,您需要包含Model.Student个项目的内容。如果每个ListItem.Value的类型为Model.Student,则可以使用:

var checkedStudents = subjectCheckBoxList.Items.Cast<ListItem>().Where(c => c.Selected)
                          .Select(c => (Model.Student)c.Value).ToList();

subjectGridView.DataSource = checkedStudents;
subjectGridView.DataBind();

答案 1 :(得分:0)

 var checkedItemList = subjectCheckBoxList.Items.Cast<ListItem>().Where(c => c.Selected).ToList();
        List<Model.Subject> list = new List<Model.Subject>();
        foreach (ListItem item in checkedItemList)
        {               
                Model.Subject aSubject = new Model.Subject();
                aSubject.ID = int.Parse(item.Value);
                aSubject.SubjectName = item.Text;
                list.Add(aSubject);
        }            
        subjectGridView.DataSource = list;  
        subjectGridView.DataBind();