[英]ListView DataItem Shows Null
几天前,我写了一篇关于在ASP.NET中实现ListView的问题 。 现在,在编写了所有其他代码的情况下,我在ListView中保存更改的项目时遇到了问题。
一些注意事项:
GetListViewItems()
方法,该方法又调用Save()
方法。 Listview.DataBind()
事件 <%#Eval("Key.Name") %>
和一个名为DropDownList
使用<%#Eval("Value") %>
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的代码。
ListViewDataItem
在Listview
每个项目是null
? Foo.Id
? Id
我会使用什么? 就像现在一样,当前ListView基于选择的Foo
来显示。 然后显示所选的那些Foo
,用户可以更改DropDownList
的Bar
,点击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。
任何对这种方法的批评,以及使其更好的方法都非常感谢。
一些快速回答:
您需要使用数据绑定来工作,换句话说,分配给DataSource
并调用DataBind()
。 编辑:似乎你正在这样做。 但请记住,它不会在回发之间持续存在,只是DataKey
(见下文)。
如果我没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.