ListView DataItem显示Null

几天前,我写了关于在ASP.NET中实现ListView的问题 。 现在,在编写了所有其他代码的情况下,我无法在ListView中保存更改的项目。

一些注意事项:

  • “保存”按钮不是ListView的一部分; 它调用GetListViewItems()方法,该方法又调用Save()方法。
  • 当按下按钮请求更新记录时,将调用Listview.DataBind()事件
  • Listview使用显示文本,使用显示名为DropDownList文本

从ListView获取项目

 public void GetListViewItems() { List Result = FooManager.CreateFooList(); DropDownList ddl = null; ListViewItem Item = null; try { foreach (ListViewDataItem item in lvFooList.Items) { Item = item; ddl = ((DropDownList) (Item.FindControl("ddlListOfBars"))); if (//something is there) { Foo foo = FooManager.CreateFoo(); foo.Id = item.DataItemIndex; //shows null int barId = int.Parse(ddl.SelectedItem.Value); //works just fine foo.barId = barId; Result.Add(foo); } } } catch (Exception ex) { //Irrelevant for our purposes } } 

DataBinding ListView

我在上一个问题中显示了数据绑定ListView的代码。

问题(S):

  1. 为什么当我遍历Listview中的Listview ,每个项都为null
  2. 如何从字典中检索Foo.Id
  3. 还有什么我可能会失踪?
  4. 如果我想根据显示的项目以编程方式获取Id我会使用什么? 就像现在一样,当前的ListView是根据选择的Foo来显示的。 然后显示所选的Foo ,用户可以更改DropDownListBar ,点击Save,然后传播这些更改。

更新

事实certificate,我的问题是莱比所说的; 那就是我需要指定DataKeyNames并使用它们来保留ListView中的信息。

这是我添加的代码:

 try { int DataKeyArrayIndex = 0; foreach (ListViewDataItem item in lvFooList.Items) { Item = item; ddl = ((DropDownList) (Item.FindControl("ddlListOfBars"))); if (//something is there) { Foo foo = FooManager.CreateFoo(); Foo tempFoo = FooManager.CreateFoo(); if (lvFooList != null) { tempFoo = ((Foo)(lvFooList.DataKeys[DataKeyArrayIndex].Value)); } foo.Id = tempFoo.Id; int barId = int.Parse(ddl.SelectedItem.Value); //works just fine foo.barId = barId; Result.Add(foo); DataKeyArrayIndex++; } } } 

然后在.ascx文件中,我添加了DataKeyNames="Key" ,如下所示:

  

这允许我使用我之前post中的Key来确定正在查看哪个Foo。

任何对这种方法的批评,以及使其更好的方法都非常感谢。

一些快速回答:

  1. 您需要使用数据绑定来工作,换句话说,分配给DataSource并调用DataBind() 。 编辑:似乎你这样做。 但请记住它不会在回发之间持续存在,只是DataKey (见下文)。

  2. 如果我没DataKeyNames ,您需要指定DataKeyNames ,然后可以从DataKey属性中检索它们。

您还可以使用ListViewDataItem.DataItemIndex属性而不是保留自己的索引,如下所示:

 foreach (ListViewDataItem item in MyListView.Items) { // in this example key is a string value Foo foo = new Foo(MyListView.DataKeys[item.DataItemIndex].Value as string); // do stuff with foo }