簡體   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