如何代表 ID 从数据列表中删除图像
本文关键字:删除 图像 列表 数据 何代表 ID | 更新日期: 2023-09-27 18:36:47
我想代表id从数据列表中删除图像,但此代码不起作用错误:索引超出范围。必须是非负数且小于集合的大小。参数名称:索引
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";
现在请将数据密钥名称添加到您的数据列表中,例如
<asp:DataList DataKeyField="id"
因此,这会将 Id 列添加到数据密钥。然后你可以在后端获得它的价值。
试试这个:你错过了。价值,我猜。
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
列
好的,
您的代码没有给我很多信息来处理,但是如果您配置了数据集,那么您可以编写一个方法来: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
您可能会在上述参数中获得空值。如果是,您可能没有在数据列表中设置数据密钥归档。
因此,您需要先在数据列表中设置DataKeyField
,然后再使用代码。