How can I get a DataItem
in a listView
in the ItemEditing
event?? I thought it would work similar to a repeater but I am at a loss. I need it to do something like this:
protected void lvUsers_ItemEditing(object sender, ListViewEditEventArgs e)
{
var item = lvUsers.Items[e.NewEditIndex];
var id = DataBinder.Eval(item.DataItem, "ID").ToString();
var name = DataBinder.Eval(item.DataItem, "Name").ToString();
}
What am I doing wrong? item.DataItem
is always null. Thanks!!
I see that I can get the id from the datakey using:
lvUsers.DataKeys[item.DataItemIndex].Value
I suppose I cou开发者_如何转开发ld query the db to get the rest of the values but since it was databound I would think I could get them without the db call.
Do I have to set every property up in datakeys??
I also tried using the OnItemCommand
same thing.
FindControl doesn't work for me either to find a dropdown in the edit template in any of these events either.
ListView is either hard to work with or I am missing a key concept.
The DataItem
object is only available during the databinding process (ItemDataBound event). After that, it no longer exists. That's why it is always null in your code.
You will have to either include the information in the DataKeys (not recommended if it's a lot of data), or use FindControl to get the value from the control in the EditItemTemplate.
You said FindControl was not working for you. Did you try doing it in the following way?
ListViewItem item = lvUsers.Items[e.NewEditIndex];
DropDownList ddl = item.FindControl("MyDDL") as DropDownList;
I haven't used ListViews in a while, but this may help:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemdatabound.aspx
It shows the way to access a value in the ItemDataBound method, but I think it is probably much the same...
protected void ContactsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
Label EmailAddressLabel;
if (e.Item.ItemType == ListViewItemType.DataItem)
{
// Display the e-mail address in italics.
EmailAddressLabel = (Label)e.Item.FindControl("EmailAddressLabel");
System.Data.DataRowView rowView = e.Item.DataItem as System.Data.DataRowView;
string currentEmailAddress = rowView["EmailAddress"].ToString();
}
See if that helps or at least gets you closer...
精彩评论