簡體   English   中英

從GridView中刪除行時索引超出范圍異常

[英]Index out of range exception while deleting row from GridView

我得到的錯誤就像

“指數超出范圍。必須是非負數且小於集合的大小”

當試圖刪除gridview行時。 我的aspx.cs代碼如下:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    try
    {
        main delete=new main();

        // int id = Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells["id"].Value);
        // string ID = GridView1.Rows[e.RowIndex].ToString();
        sQLcONN.Open();
        string Query = "delete  * from shoppingcart where shoppingcart.with_puja = '"+Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString())+"' ";
        delete.deleteData(Query);
        Bindgrid();
        sQLcONN.Close();
    }
    catch (Exception ex)
    {
        Console.WriteLine("{0} Exception caught.", ex);
    }
}

也許DataKeys部分是罪魁禍首,它必須是這樣的:

string Query = "delete from shoppingcart where shoppingcart.with_puja = '" + Convert.ToInt32(e.Item.DataKeys["nameOfKey"].Value).ToString() + "'";

或類似的東西:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    try
    {
        main delete = new main();
        DataTable dt = GridView1.DataSource as DataTatable;

        sQLcONN.Open();
        string Query = "delete from shoppingcart where shoppingcart.with_puja = '" + Convert.ToInt32(dt.Rows[e.RowIndex]["nameOfKey"]).ToString() + "'";
        delete.deleteData(Query);
        Bindgrid();
        sQLcONN.Close();

    }
    catch (Exception ex)
    {
        Console.WriteLine("{0} Exception caught.", ex);
    }
}

nameOfKey是作為表的列名with_puja你的情況和GridView1必須e.Item如果eItem屬性。

GridView DataKeys就像:

 DataKeyNames="Id, foo, foo"

然后嘗試使用這樣的字符串:

Convert.ToInt32(GridView1.DataKeys[e.RowIndex][0].ToString()); // 0 is the index and in this case Id will be at zero

好吧,這個問題讓Bejebus感到厭煩,但直到今天才弄明白。

我的情況:

  • 一個數據庫新手。

  • 設置我自己的數據庫。

  • 使用ASP.NET與MySQL,phpMyAdmin

  • 出於某種原因,我的桌子中只有一個有這個問題。


在搜索解決方案時,我決定打開我的數據庫並將有問題的表的存儲引擎從MyISAM更改為InnoDB

僅這一點就解決了這個問題。

但這只是真正問題的線索 就我而言,有問題的表格更加重讀,只是偶爾改變,所以MyISAM就是我想要的。

這里的關鍵區別是MyISAM對輸入更嚴格。 正如您在上面所看到的,有很多Int32轉換正在進行中。 所以,試試這個:

  • 打開你的數據庫,表
  • 檢查表格的id字段
  • 它的類型是某種形式的“Int”
  • Value / Length字段是否為32以外的值?

希望能為他人節省一些時間和悲傷。

您可以將行索引作為CommandArgument傳遞。

在服務器上的事件方法中:

int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.grid.DataKeys[rowIndex]["myKey"];

在按鈕上使用:

CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'

編輯:

查詢:

string Query = "delete  * from shoppingcart where shoppingcart.with_puja = '"+val +"' ";

我建議使用參數來避免sql注入

嘗試這個

string Query = "delete * from shoppingcart where shoppingcart.with_puja = '" + Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["Id"].ToString()) + "'";

sum + = Convert.ToInt32(GridView1.Rows [i] .Cells [3] .Text);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM