Okay so I have ListView and I am having some issues removing an item from the listview and the database. I am trying to accomplish this using OnItemDeleting. When I run it, it returns as having been successful; however, it was not so I am guessing that I am still not retrieving my selected imageId from DataKeyNames(for some reason). Any suggestions?
Here is my List View:
<asp:ListView ID="ListView2" runat="server" GroupItemCount="3" DataKeyNames="ImageId" OnItemDeleting="ListView2_ItemDeleting">
Here is the link button:
<asp:LinkButton runat="server" Id="lvBtn" CommandName="Delete" Text="Remove" OnClientClick="return confirm('Remove this image?')"/>
Here is my codebehind C#:
protected void ListView2_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
string programId = Request.QueryString["ProgramId"];
ListView2.SelectedIndex = Convert.ToInt32(e.ItemIndex);
string imageId = ListView2.DataKeys[e.ItemIndex].Value.ToString();
// Execute the delete command
bool success = CatalogAccess.DeleteProgramImageRelation(imageId, programId);
ListView2.EditIndex = -1;
// Display status message
statusLabel2.Text = success ? "Image removed successfully" : "Failed to remove image";
// Reload the grid
DataBind();
}
Catalog Access:
// Delete program image relationship
public static bool DeleteProgramImageRelation(string ProgramId, string ImageId)
{
// get a configured DbCommand object
DbCommand comm = GenericDataAccess.CreateCommand();
// set the stored procedure name
comm.CommandText = "DeleteProgramImageRelation";
// create a new parameter
DbParameter param = comm.CreateParameter();
param.ParameterName = "@ProgramId";
param.Value = ProgramId;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// create a new parameter
param = comm.CreateParameter();
param.ParameterName = "@ImageId";
param.Value = ImageId;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// execute the stored procedure;
int result = -1;
try
{
result = GenericDataAccess.ExecuteNonQuery(comm);
}
catch
{
// any errors are logged in DataAccess, we ignore them here
}
// result will be 1 in case of success
return (result != -1);
}
Problem solved! turns out my ProgramId was the id not being captured so I made small tweak like so:
I then just updated the rest of my references accordingly, and it works perfect now.