[英]Link button Delete from ListView and DB in C#
好的,所以我有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);
設置斷點來嘗試調試result = GenericDataAccess.ExecuteNonQuery(comm);
並進行驗證。
從您發布的方法CatalogAccess.DeleteProgramImageRelation(imageId, programId)
代碼中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"];
然后,我相應地更新了其余的參考文獻,現在可以正常使用了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.