前几天,我 写了有关问题的文章 在 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
     }
}

数据绑定ListView

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

问题):

  1. 为什么当我迭代时 ListViewDataItem 在里面 Listview 每个项目都是 null?
  2. 我怎样才能取回 Foo.Id 来自字典?
  3. 我还可能缺少什么?
  4. 如果我想得到它我会用什么 Id 根据显示的项目以编程方式进行?现在,当前的 ListView 是根据什么显示的 Foos 被选中。那些 Foo然后显示所选的内容,用户可以更改 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++;
     }
   }
}

然后在 .ascx 文件,我添加了 DataKeyNames="Key", ,像这样:

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

这使我能够使用 Key 从我之前的帖子 确定正在查看哪个 Foo。

非常感谢对这种方法的任何批评以及改进方法。

有帮助吗?

解决方案

一些快速答案:

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

  2. 如果我没记错的话,您需要指定 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归因
不隶属于 StackOverflow
scroll top