ListView DataItem显示Null

Geo*_*ker 19 c# asp.net listview

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

一些注意事项:

  • "保存"按钮不是ListView的一部分; 它调用GetListViewItems()方法,然后调用该Save()方法.
  • Listview.DataBind()当按下按钮请求更新记录时,将调用该事件
  • Listview显示文本使用<%#Eval("Key.Name") %>和命名DropDownList使用<%#Eval("Value") %>

从ListView获取项目

public void GetListViewItems()
{
 List<Foo> 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
     }
}
Run Code Online (Sandbox Code Playgroud)

DataBinding ListView

在我之前的问题中显示了数据绑定ListView的代码.

问题(S):

  1. 为什么,当我通过迭代ListViewDataItem的Listview每一个产品null?
  2. 如何Foo.Id从词典中检索?
  3. 我还能错过什么?
  4. 如果我想Id根据显示的项目以编程方式获得该怎么办?就像现在一样,当前的ListView会根据Foo选择的内容显示.那些Foo选择s的则显示,用户可以改变Bar的DropDownList,点击保存,以及这些变化将会传播.

更新

事实证明,我的问题是莱比所说的; 那就是我需要指定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++;
     }
   }
}
Run Code Online (Sandbox Code Playgroud)

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

<asp:ListView ID="lvFooList" runat="server" DataKeyNames="Key">
Run Code Online (Sandbox Code Playgroud)

这允许我使用Key 我之前的帖子来确定正在查看哪个Foo.

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

lep*_*pie 12

一些快速回答:

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

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


小智 6

您还可以使用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
}
Run Code Online (Sandbox Code Playgroud)