Go4Expert (http://www.go4expert.com/)
-   ASP.NET (http://www.go4expert.com/forums/asp-net/)
-   -   Deleting from GridView using checkbox selections (C#) (http://www.go4expert.com/forums/deleting-gridview-using-checkbox-t26515/)

Jymoz 17Aug2011 18:33

Deleting from GridView using checkbox selections (C#)
I have a gridview (just called GridView1) containing a selection of tasks that the user can add to and edit etc. I've added in checkboxes so that the user can select multiple rows at once and the hope is that they can then click on a button to delete those rows.

I picked up some code on the internet that allows me to go through the check boxes, see which ones are checked and then return to a label which tasks would be deleted. It didn't provide the code for actually deleting them however and i havent been able to find out how to do it, so i was hoping someone could help me.

My code is below:


protected void DeleteButton_Click(object sender, GridViewDeleteEventArgs e)
      bool AtLeastOneRowDeleted = false;
      foreach (GridViewRow row in GridView1.Rows)
              CheckBox cb = (CheckBox)row.FindControl("chk1");
              if (cb != null && cb.Checked)
                    AtLeastOneRowDeleted = true;
                    string TaskName = Convert.ToString(GridView1.DataKeys[row.RowIndex].Value);
                    DeleteResults.Text += string.Format("This would have deleted task - {0} <br />", TaskName);
                    DeleteResults.Visible = AtLeastOneRowDeleted;

I'm linking the gridview by a SQLDataSource linked to a SQL Server 2008 database. I'll probably have to link to it to delete it from there but when i've started to try that they come back with immediate errors.

Any help would be greatly appreciated

Christopherwilde 10Nov2012 15:38

Re: Deleting from GridView using checkbox selections (C#)
Nice try and very interesting topic you can use code:

Using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Text;

Here’s the code block for deleting multiple records

#region Multiple Delete
private void DeleteRecords(StringCollection sc)
  SqlConnection conn = new SqlConnection(GetConnectionString());
  StringBuilder sb = new StringBuilder(string.Empty);
  foreach (string item in sc)
    const string sqlStatement = "DELETE FROM Customers WHERE CustomerID";
    sb.AppendFormat("{0}='{1}'; ",sqlStatement, item);
            SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
            cmd.CommandType = CommandType.Text;
    catch (System.Data.SqlClient.SqlException ex)
            string msg = "Deletion Error:";
            msg += ex.Message;
            throw new Exception(msg);

alia123 16Jan2016 14:32

Re: Deleting from GridView using checkbox selections (C#)
Hey,here's the link I'm sharing just go through it:

All times are GMT +5.5. The time now is 02:26.