简体   繁体   中英

Error in deleting record from GridView

I have a GridView control with the following markup:

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

model of this grid is a List of Group class. Group class is as follows:

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

GroupId is primary key of my table. When I press Delete button, I get the following error:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

my RowDeleting event handler codes:

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。

the code looks correct but the event chosen is not . as @AVD mentioned RowDeleting event is for per row situation where each row has its own Delete button :

Occurs when a row's Delete button is clicked, but before the GridView control deletes the row

all you need is to add a btnRemove_Click event and put your code there .

If you want to do the multiple delete add a button called multiple delete outside the gridview and handle the onclick event, in the event handler delete the number of items that are selected like below

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();

        }

You can delete according to your primary key in the stored procedure Hope this helps :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM