链接按钮从C#中的ListView和DB中删除

时间:2015-06-08 17:46:47

标签: c# asp.net listview

好的,所以我有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);
}

2 个答案:

答案 0 :(得分:0)

我不确定你在做什么,但我相信你得到了一些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

答案 1 :(得分:0)

问题解决了!事实证明我的ProgramId是没有被捕获的id所以我做了一些小调整:

    private string currentProgramId;

    protected void Page_Load(object sender, EventArgs e)
    {
        currentProgramId = Request.QueryString["ProgramId"];

然后我相应地更新了其余的引用,现在它完美无缺。