我有一个ListBox,我已经绑定了项目,但是当我稍后尝试从ListBox中检索对象时,我得到一个编译错误......有谁知道这笔交易是什么?
protected void Page_Load(object sender, EventArgs e)
{
List<Project> projects;
DeleteListBox.ItemType = "Project";
DeleteListBox.DataValueField = "projName";
using(DBMethods db = new DBMethods())
{
//Projects is not null during testing
projects = db.getProjects() as List<Project>;
DeleteListBox.DataSource = projects;
DeleteListBox.DataBind();
}
}
现在稍后我试图从ListBox中检索对象,但是在整行代码下我得到了一条红色的波浪线:
protected void PermDelete_Click(object sender, EventArgs e)
{
using(DBMethods db = new DBMethods())
{
//Compiler error here
var toDelete = DeleteListBox.SelectedItem as Project;
}
}
如何在没有编译器错误的情况下将我选择的列表项转换为Project对象?无法转换类型&#39; SystemW.Web.UI.WebControls.ListItem&#39;到&#39;项目&#39;通过参考转换...
答案 0 :(得分:0)
您无法将ListBox项目转换回自定义类,ListItem
基本上是具有两个字符串的键值对。
您必须在ListBox中存储一个与Project
类中的属性匹配的标识符(在此示例中为属性ID
)。
DeleteListBox.DataSource = projects;
DeleteListBox.DataTextField = "Name";
DeleteListBox.DataValueField = "ID";
DeleteListBox.DataBind();
然后单击该按钮时,循环ListBox中的所有ListItem,检查选择了哪些ListItem,并在Project
项目列表中找到正确的Linq
。
protected void PermDelete_Click(object sender, EventArgs e)
{
foreach (ListItem item in DeleteListBox.Items)
{
if (item.Selected)
{
var toDelete = projects.Where(x => x.ID == Convert.ToInt32(item.Value)).FirstOrDefault();
}
}
}