ListView DataIitem은 null을 보여줍니다
문제
며칠 전, i 문제에 대해 썼습니다 ASP.NET에서 ListView를 구현하여 이제 다른 모든 코드가 작성된 상태에서 ListView에서 변경된 항목을 저장하는 데 어려움을 겪고 있습니다.
몇 가지 주목 :
- 저장 버튼은 ListView의 일부가 아닙니다. 그것은
GetListViewItems()
방법으로 전화를 걸어Save()
방법. - 그만큼
Listview.DataBind()
버튼을 누르면 이벤트가 호출되어 레코드를 업데이트 할 레코드를 요청합니다. - ListView는 텍스트 사용을 보여줍니다
<%#Eval("Key.Name") %>
그리고 a 명명 된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 Databind 코드는 다음과 같습니다 내 이전 질문에 여기에 표시됩니다.
질문):
- 내가 반복 할 때 왜 그런가?
ListViewDataItem
에서Listview
각 항목은null
? - 어떻게 검색 할 수 있습니까?
Foo.Id
사전에서? - 내가 무엇을 놓칠 수 있습니까?
- 내가 얻고 싶다면 무엇을 사용합니까?
Id
어떤 항목이 표시되었는지 프로그래밍 방식으로? 지금과 같이 현재 ListView는 무엇을 기반으로 표시됩니다.Foo
S가 선택되었습니다. 저것들Foo
그런 다음 선택한 S가 표시되고 사용자는Bar
에서DropDownList
, 저장을 누르면 이러한 변경 사항이 전망됩니다.
업데이트
결과적으로, 내 문제는 무엇이 었습니다 leppie 말했다; 그리고 그것은 내가 지정해야한다는 것이 었습니다 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가보고 있는지 결정하기 위해.
이 접근법에 대한 비판과 그것을 개선하기위한 방법은 크게 높이 평가됩니다.
해결책
몇 가지 빠른 답변 :
작동하기 위해 Databinding을 사용해야합니다. 다시 말하면
DataSource
그리고 전화DataBind()
. 편집 : 당신이 그렇게하고있는 것 같습니다. 그러나 그것은 포스트 백 사이에 지속되지 않는다는 것을 기억하십시오.DataKey
(아래 참조).내가 올바르게 기억한다면, 당신은
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
}