0
votes
<asp:GridView EnableViewState="true" DataKeyNames="ID" style="width:100%;" ID="tableUsers" runat="server"  CssClass="table table-striped table-bordered" AllowSorting="True" AllowPaging="True" OnPageIndexChanging="tableUsers_PageIndexChanging" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" OnRowDeleting="tableUsers_RowDeleting" OnRowEditing="tableUsers_RowEditing" AutoGenerateColumns="False" OnRowCancelingEdit="tableUsers_RowCancelingEdit" OnRowUpdating="tableUsers_RowUpdating" OnSorting="tableUsers_Sorting">
                                        <Columns>
                                            <asp:TemplateField HeaderText="ID" Visible="False">
                                                <ItemTemplate>
                                                    <asp:Label ID="txtID" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField HeaderText="Username">
                                                <EditItemTemplate>
                                                    <asp:TextBox ID="txtUsername" runat="server" Text='<%# Eval("Username") %>'></asp:TextBox>
                                                </EditItemTemplate>
                                                <ItemTemplate>
                                                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("Username") %>'></asp:Label>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField>
                                              <ItemTemplate>
                                                <asp:CheckBox ID="deleteBox" runat="server" Enabled="true"/>
                                              </ItemTemplate>
                                           </asp:TemplateField>

                                        </Columns>

                                    </asp:GridView>
 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
           tableFill();
        }

    }
protected void Button2_Click(object sender, EventArgs e)
    {
        try
        {
            bool checkedfound = false;
            foreach (GridViewRow grow in tableUsers.Rows)
            {
                //Searching CheckBox("chkDel") in an individual row of Grid  
                CheckBox chkBx = (CheckBox)grow.FindControl("deleteBox");
                //If CheckBox is checked than delete the record with particular empid  
                if (chkBx != null && chkBx.Checked)
                {
                    string id = tableUsers.DataKeys[grow.RowIndex].Values["ID"].ToString();
                    master.execute("DELETE FROM Users WHERE ID='" + id + "'", "User Deleted", "ERROR");
                    checkedfound = true;
                }
            }  

            if(checkedfound){
                alert("Selected users deleted", true);
                tableFill();
            }
            else
            {
                alert("no checks found",false);
            }
        }
        catch (Exception x)
        {
            alert("Delete Fail: "+x.ToString(), false);
        }
    }
protected void tableUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            string id = tableUsers.DataKeys[e.RowIndex].Values["ID"].ToString();
            master.execute("DELETE FROM Users WHERE ID='" + id + "'", "User Deleted", "ERROR");
            alert("User deleted",true);
            tableFill();
        }
        catch (Exception)
        {
            alert("Delete Failed",false);
        }
    }
 private void tableFill()
    {
        string constr = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
        using (MySqlConnection con = new MySqlConnection(constr))
        {
            using (MySqlCommand cmd = new MySqlCommand("SELECT ID,Username,Email,Rank,IP FROM Users"))
            {
                using (MySqlDataAdapter sda = new MySqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        tableUsers.DataSource = dt;
                        tableUsers.DataBind();
                    }
                }
            }
        }


    }

Trying to delete multiple rows upon Buttob2 click. However, i keep recieving the error of "no checks found". Ive tried adding the !postback in the load but still no luck. I have also coppied others code on the same issue and the only responses are to add the !postback

(The gridview loads the data fine and tableUsers_RowDeleting works)

1
I would set a breakpoint inside of button2_click and step through the code (press F10 once the program breaks at the breakpoint). You can step through and follow the loop and see where your issue may be. This is a lot of code that would require a connection to a database in order to copy and fix on my end, so this is the best advice I can offer. Good luck. - Taylor Brown
you are running "tableUsers_RowDeleting" which redraws the grid before you are actually looping through the grid in "Button2_Click" - DaniDev
@DaniDev removing the rowdeleting didnt work - chris
I think you may have more than one issue and your "try" sequence (in Button2_Click) is too large so you are possibly hitting an error before you are setting checkedfound = true; (as Taylor suggested) You have to step through the code to see what is happening. - DaniDev
Hope you found your solution? "Do you think the post back is causing the unchecking" that seems like a likely scenario or maybe you are not finding the check control ? there could be numerous issues, that is why you should step through the code. Can you do that in your development environment? - DaniDev

1 Answers

0
votes

If I understand your issue, you would like to select multiple rows at once and delete those record on single button click.

Could you attempt this code:

This way you may exclude using separate row deleting event and you may not need to keep EnableViewState property.

protected void btnDelete_Click(object sender, EventArgs e)   
{   
     foreach (GridViewRow row in GridViewEmployee.Rows)   
        {   
          if ((row.FindControl("chkSelect") as CheckBox).Checked)   
          {   
               int recordid = Convert.ToInt32(gridview.DataKeys[row.RowIndex].Value);   
               using (SqlConnection con = new SqlConnection(@"Data Source=mssql; Initial Catalog=dbname; Uid=sa; pwd=sa;"))   
               {   
                   con.Open();   
                   SqlCommand cmd = new SqlCommand("DELETE FROM `[table]` WHERE ID=" + recordid, con);   
                   cmd.ExecuteNonQuery();   
                   con.Close();   
               }   
           }   
       }
    BindGrid();   
}

I hope this helps or gives some insight.

UPDATE:

List<int> list = new List<int>(); 
    if (ViewState["SelectedRecords"] != null) 
    { 
        list = (List<int>)ViewState["SelectedRecords"]; 
    } 
    foreach (GridViewRow row in GridView1.Rows) 
    { 
        CheckBox chk = (CheckBox)row.FindControl("chkSelect"); 
        var selectedKey = 
        int.Parse(GridView1.DataKeys[row.RowIndex].Value.ToString()); 
        if (chk.Checked) 
        { 
            if (!list.Contains(selectedKey)) 
            { 
                list.Add(selectedKey); 
            } 
        } 
        else 
        { 
            if (list.Contains(selectedKey)) 
            { 
                list.Remove(selectedKey); 
            } 
        } 
    } 
    ViewState["SelectedRecords"] = list; 
    //BindGrid(); 
}