繁体   English   中英

如何从datalist代表id删除图像?

[英]how to delete image from datalist behalf of id?

我想代表id删除datalist中的图像,但此代码不起作用错误:索引超出范围。 必须是非负数且小于集合的大小。 参数名称:index

public void show_top_one()
{
    BusinessLogic b1 = new BusinessLogic();
    string query = "select txt_img_name from tbl_gallery2";
    DataSet ds = b1.GetDataSet(query);
    DataList1.DataSource = ds.Tables[0];
    DataList1.DataBind();
}

protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
{
    BusinessLogic b1 = new BusinessLogic();
    int id = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
    string query = "Delete from tbl_gallery2 where id='"+id+"'";
    b1.ExecuteQuery(query);
    show_top_one();

}

}

请更改您的选择查询。

string query = "select id,txt_img_name from tbl_gallery2";

现在请将DataKeyName添加到您的datalist中

<asp:DataList DataKeyField="id"

所以这会将Id列添加到datakey。 然后你可以在后端获得它的价值。

试试这个:你错过了。我想是真的。

protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
{
    BusinessLogic b1 = new BusinessLogic();
    int id = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex].Value);
    string query = "Delete from tbl_gallery2 where id='"+id+"'";
    b1.ExecuteQuery(query);
    show_top_one();

}

如果是int,则不需要单引号

 string query = "Delete from tbl_gallery2 where id="+id;

您还需要在选择查询中选择id列以及数据键

好的,你的代码并没有给我很多信息,但如果你已经配置了DataSet,那么你可以编写一个方法:1。通过id获取图像。 2.删除所选图像。

 public "classname where the image is" GetById(int id)
    {
        return ds.Find(id);  //ds is your DataSet
    }

并在找到它之后

 public void Delete(int id)
    {
        var entity = this.GetById(id);
        if (entity!=null)
        {
            this.Delete(entity);
        }
    }

这应该是一个干净,很好的答案:)

祝好运!

首先,您需要检查此值

 DataList1.DataKeys[e.Item.ItemIndex].Value

您可能在上面的参数中获得null值。 如果是,您可能没有在数据列表中设置数据密钥字段。

因此,您需要DataKeyField在DataList中设置DataKeyField ,然后再使用该代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM