簡體   English   中英

從GridView刪除記錄時出錯

[英]Error in deleting record from GridView

我有一個帶有以下標記的GridView控件:

 <asp:GridView ID="gvGroups" runat="server" Width="100%" AutoGenerateColumns="False"
            ShowFooter="True" BorderColor="White" BorderStyle="Ridge" CellSpacing="1" BorderWidth="2px"
            BackColor="White" CellPadding="3" GridLines="None" Font-Names="Tahoma" Font-Size="11px"
            DataKeyNames="GroupId" OnRowDeleting="gvGroups_RowDeleting">
            <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
            <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
            <Columns>
                <asp:TemplateField HeaderText="Row">
                    <ItemTemplate>
                        <asp:Literal ID="litRowNumberNormal" runat="server"></asp:Literal>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:Literal ID="litRowNumberFooter" runat="server"></asp:Literal>
                    </FooterTemplate>
                    <ItemStyle HorizontalAlign="Center" />
                    <FooterStyle HorizontalAlign="Center" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Title">
                    <ItemTemplate>
                        <%#Eval("Title")%>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAddTitle" runat="Server" BorderStyle="Solid" BorderWidth="1px"
                            Font-Names="Tahoma" Font-Size="11px" BorderColor="Black" />
                    </FooterTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEditTitle" Text='<%# Bind("Title") %>' runat="server" BorderStyle="Solid"
                            BorderWidth="1px" Font-Names="Tahoma" Font-Size="11px" BorderColor="Black" />
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" ButtonType="Button" UpdateText="Save" CancelText="Cancel"
                    EditText="Edit" HeaderText="Edit">
                    <FooterStyle BackColor="#669900" HorizontalAlign="Center" />
                    <HeaderStyle BackColor="#5A49A7" HorizontalAlign="Center" />
                    <ItemStyle BackColor="#FFC080" HorizontalAlign="Center" />
                </asp:CommandField>
                <asp:TemplateField HeaderText="Delete">
                    <FooterTemplate>
                        <asp:Button CommandName="Delete" Text="Delete" ID="btnRemove" runat="server" BorderStyle="Solid"
                            BorderWidth="1px" BackColor="#FFC080" Font-Names="Tahoma" Font-Size="11px" />
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="ChkRemove" runat="server"></asp:CheckBox>
                    </ItemTemplate>
                    <ItemStyle BackColor="LightCoral" HorizontalAlign="Center" />
                    <HeaderStyle BackColor="#5A49A7" HorizontalAlign="Center" />
                    <FooterStyle BackColor="#669900" HorizontalAlign="Center" />
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

該網格的模型是Group類的List。 組類如下:

public class Group
{
 public int GroupId {get; set; }
 public string Title {get; set; }
}

GroupId是表的主鍵。 當我按Delete按鈕時,出現以下錯誤:

索引超出范圍。 必須為非負數並且小於集合的大小。
參數名稱:索引

我的RowDeleting事件處理程序代碼:

protected void gvGroups_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    CheckBox chkRemove;

    List<int> ids = new List<int>();


    foreach (GridViewRow gvRow in gvGroups.Rows)
    {
        chkRemove = (CheckBox)gvRow.FindControl("ChkRemove");
        if (chkRemove.Checked)
        {
            ids.Add(Int32.Parse(gvGroups.DataKeys[gvRow.RowIndex].Value.ToString()));
        }
    }

    if (ids.Any())
    {
        GroupService.DeleteGroupById(ids);
    }

    this.BindGroups();
}

我們可以做的另一項工作是將“刪除”按鈕的CommandName屬性更改為“刪除”以外的任何內容,並在RowCommand事件中對其進行處理,“ Delete”命令是用於觸發GridView控件的RowDeleting事件的默認CommandName。

代碼看起來正確,但是選擇的事件不正確。 正如@AVD提到的那樣,RowDeleting事件適用於per row情況,其中每row都有自己的Delete button

單擊某行的“刪除”按鈕時,但在GridView控件刪除該行之前發生

您所需btnRemove_Click只是添加一個btnRemove_Click事件並將代碼放在此處。

如果要進行多次刪除,請在gridview外部添加一個名為“多次刪除”的按鈕並處理onclick事件,在事件處理程序中,刪除選擇的項數,如下所示

public void DeleteEverything(object sender, EventArgs e)
    {
        // this function is to delete the selected items based on the checkbox
        CheckBox chkAll = (CheckBox)GridView1.HeaderRow.FindControl("SelectAllCheck");
        // to get the Checkbox status in the header rows
        if (chkAll.Checked == true)
        {
            int i = 0;
            foreach (GridViewRow gvRow in GridView1.Rows)//to get all rows in that particular page
            {
                string Delete = Convert.ToString(GridView1.Rows[i].Cells[3].Text);
                //Cells[3] is the column to get one by one rows cells[3] columns where you should keep your primary keys and in visible state
                Bal_add.Delete(Delete);
                i++;
            }
            Response.Redirect("Information.aspx");
        }
        else
        {
            int j=0;
            foreach (GridViewRow gvRow in GridView1.Rows)
            {
                CheckBox chkSel = (CheckBox)gvRow.FindControl("SelectCheck");
                if (chkSel.Checked == true)
                {
                    string Delete = Convert.ToString(GridView1.Rows[j].Cells[3].Text);
                    //Cells[3] is the column to get one by one rows cells[3] columns where you should keep your primary keys and in visible state
                    Delete(Delete);

                }
                j++;

            }
            Response.Redirect("Information.aspx");
        }

    }

public void Delete(string UserEmail)
        {
            obj_add = new add();
            string QueryString;
            QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["Admin_raghuConnectionString1"].ToString();

            obj_SqlConnection = new SqlConnection(QueryString);

            obj_SqlCommand = new SqlCommand("usp_DeleteDataProcedure");
            obj_SqlCommand.CommandType = CommandType.StoredProcedure;
            obj_SqlConnection.Open();

            obj_SqlCommand.Parameters.AddWithValue("@UserEmail", UserEmail);//here @UserName is the variable that we declare in the stored procedure
            obj_SqlCommand.Connection = obj_SqlConnection;
            SqlDataReader obj_result = null;

            obj_SqlCommand.CommandText = "usp_DeleteDataProcedure";
            obj_result = obj_SqlCommand.ExecuteReader();
            obj_SqlConnection.Close();

        }

您可以根據存儲過程中的主鍵刪除,希望對您有所幫助:D

暫無
暫無

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

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