C# 如何代表id从数据列表中删除图像?
我想代表id从数据列表中删除图像,但此代码无效 错误:索引超出范围。必须为非负数且小于集合的大小。参数名称:索引C# 如何代表id从数据列表中删除图像?,c#,asp.net,C#,Asp.net,我想代表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.DataSou
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();
}
}试试这个:你错过了。我想是有价值的
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;
您还需要在select查询中选择
id
列以及数据键请更改select查询
string query = "select id,txt_img_name from tbl_gallery2";
现在请将DataKeyName添加到您的数据列表中,如
<asp:DataList DataKeyField="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
您可能会在上述参数中获得null值。如果是,您可能没有在数据列表中设置数据密钥
因此,您需要首先在数据列表中设置DataKeyField
,然后使用代码。strange首先转换为Int32,然后在参数中以单引号传递它??我写了一半,看到了您的帖子。OP select查询表明未分配DataKeyField属性+1检查此值DataList1.DataKeys[e.Item.ItemIndex]
是否为空。