从c#中的ListView和DB中删除链接按钮
本文关键字:删除 链接 按钮 DB 中的 ListView | 更新日期: 2023-09-27 17:54:13
好的,所以我有ListView,我有一些问题从ListView和数据库中删除一个项目。我正试图使用OnItemDeleting来实现这一点。当我运行它时,它返回成功;然而,事实并非如此,我猜我仍然没有从DataKeyNames(出于某种原因)检索我所选择的imageId。有什么建议吗?
这是我的列表视图:
<asp:ListView ID="ListView2" runat="server" GroupItemCount="3" DataKeyNames="ImageId" OnItemDeleting="ListView2_ItemDeleting">
链接按钮:
<asp:LinkButton runat="server" Id="lvBtn" CommandName="Delete" Text="Remove" OnClientClick="return confirm('Remove this image?')"/>
下面是我的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();
}
目录访问: // 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);
}
我不知道你到底在做什么,但我相信你得到了一些SQLException
。尝试通过在result = GenericDataAccess.ExecuteNonQuery(comm);
中放置一个断点来调试并验证它。
从你发布的CatalogAccess.DeleteProgramImageRelation(imageId, programId)
方法代码来看,你的过程期望INT
类型参数,而你正在传递String
类型参数,如下所示
DbParameter param = comm.CreateParameter();
param.ParameterName = "@ProgramId";
param.Value = ProgramId; -- ProgramId is String
param.DbType = DbType.Int32; -- You are specifying Int32
问题解决了!原来我的ProgramId是id没有被捕获,所以我做了一个小调整,像这样:
private string currentProgramId;
protected void Page_Load(object sender, EventArgs e)
{
currentProgramId = Request.QueryString["ProgramId"];
然后我只是更新了我的引用的其余部分,它现在工作完美。