Reputation: 697
I an building a webforms page and making a lot of progress with web searches and help from the Stack Overflow community, but I have hit another snag that is likely due to my own inexperience.
Here is my ListView opening tag:
<asp:ListView ID="lvLeadershipPositions"
DataKeyNames="ID"
InsertItemPosition="LastItem"
runat="server"
ItemType="BusinessLogic.Alumni.Outreach.ServicePosition"
SelectMethod="lvLeadershipPositions_GetData"
InsertMethod="lvLeadershipPositions_InsertItem"
UpdateMethod="lvLeadershipPositions_UpdateItem"
DeleteMethod="lvLeadershipPositions_DeleteItem">
and here is the code behind for the SelectMethod
, InsertMethod
, UpdateMethod
and DeleteMethod
:
public IEnumerable<ServicePosition> lvLeadershipPositions_GetData()
{
if (alumn == null)
{
alumn = new Alumn();
}
return alumn.LeadershipRoles;
}
public void lvLeadershipPositions_InsertItem()
{
var item = new BusinessLogic.Alumni.Outreach.ServicePosition();
TryUpdateModel(item);
if (ModelState.IsValid)
{
// Save changes here
item.ID = alumn.LeadershipRoles.Count;
alumn.LeadershipRoles.Add(item);
}
}
// The id parameter name should match the DataKeyNames value set on the control
public void lvLeadershipPositions_UpdateItem(int id)
{
ServicePosition item = alumn.LeadershipRoles.Find(x => x.ID == id);
// Load the item here, e.g. item = MyDataLayer.Find(id);
if (item == null)
{
// The item wasn't found
ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
return;
}
TryUpdateModel(item);
if (ModelState.IsValid)
{
// Save changes here, e.g. MyDataLayer.SaveChanges();
}
}
// The id parameter name should match the DataKeyNames value set on the control
public void lvLeadershipPositions_DeleteItem(int id)
{
int count = alumn.LeadershipRoles.Count(x => x.ID == id);
if (count == 1)
{
int removeID = alumn.LeadershipRoles.Where(x => x.ID == id).First().ID;
alumn.LeadershipRoles.RemoveAt(removeID);
return;
}
else if (count == 0)
{
ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
return;
}
else
{
ModelState.AddModelError("", String.Format("More than one Item with id {0} was found", id));
}
}
The first three methods all do exactly what I expect. For example, when clicking the update button on my page, the lvLeadershipPositions_UpdateItem
method is called, and then the lvLeadershipPositions_GetData
method is called.
And when I click the delete button lvLeadershipPositions_DeleteItem
is called but lvLeadershipPositions_GetData
is never called, so the page does not update to reflect my deletion.
What have I left out?
Upvotes: 1
Views: 100
Reputation: 5123
I think you have removed the item from the data source but you haven't rebound the list view.
Force a rebind with lvLeadershipPositions.DataBind() or call your method TryUpdateModel(item) where maybe there is the DataBind call.
Upvotes: 1