繁体   English   中英

ListView DataItem显示Null

[英]ListView DataItem Shows Null

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

一些注意事项:

  • “保存”按钮不是ListView的一部分; 它调用GetListViewItems()方法,该方法又调用Save()方法。
  • 当按下按钮请求更新记录时,将调用Listview.DataBind()事件
  • 列表视图显示文本使用<%#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
     }
}

DataBinding ListView

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

问题(S):

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

更新

事实证明,我的问题是比所说的; 那就是我需要指定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" ,如下所示:

<asp:ListView ID="lvFooList" runat="server" DataKeyNames="Key">

这允许我使用我之前帖子中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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM