Click here to Skip to main content
15,923,051 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wish to ask how i can delete the both database and selected row from data grid view by using C# windows form button??
Posted
Updated 7-Nov-13 14:58pm
v2

Your .aspx page grid code.
C#
<asp:templatefield headertext="Action" xmlns:asp="#unknown">
   <itemtemplate>                   
      <asp:linkbutton id="lblDelete" runat="server" commandname="DeleteRecord" commandargument="<%#Eval("Id") %>">Delete</asp:linkbutton>
   </itemtemplate>
</asp:templatefield>

And Note that...

Here don't use commandname="Delete/delete/DELETE".
This are inbuilt keywords. IF you use this keywords it will call OnDelete event not OnRowCommand.
This will occur runtime exception that OnDelete event was not handled.  

Your Code To Delete the record.
C#
protected void GVCategories_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int id = Convert.ToInt32(e.CommandArgument.ToString());

        //If Commandname == Delete Record then We will Proceed to delete the record
        if (e.CommandName == "DeleteRecord")
        {

            int result = 0;
            SqlCommand cmd = new SqlCommand();

           try
           {
               if (conn.State == ConnectionState.Closed)
               {
                   conn.Open();
               }

               cmd.CommandText = "DeleteCategory";
               cmd.CommandType = CommandType.StoredProcedure;
               cmd.Connection = conn;
               cmd.Parameters.Add(new SqlParameter("@ID", id));
               cmd.CommandTimeout = 10;
               result = cmd.ExecuteNonQuery();

            }
            catch (Exception ex)
            {
               Console.WriteLine("Error occured in DAL.DeleteSelectedRow() \nMessage : " + ex.Message + "InnerException : " + ex.InnerException);
            }
            finally
            {
               cmd.Dispose();
               conn.Close();
            }
            
        }
        
    }


Here your Half work is done.
This will delete data from database.
And to refresh the Grid what you need is get fresh data from database and bind the grid with that fresh data.


Hope This Help You
--------------------
Pratik Bhuva
 
Share this answer
 
v5
C#
private void btnDelete_Click(object sender, EventArgs e)
      {
          int i = 0;
          string str;
          List<int> ChkedRow = new List<int>();
          for (i = 0; i <= dataGridView1.Rows.Count - 1; i++)
          {
              if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Col1"].Value) == true)
              {
                  ChkedRow.Add(i);
              }
          }
          if (ChkedRow.Count == 0)
          {
              MessageBox.Show("Select one checkbox");
              return;
          }

          foreach (int j in ChkedRow)// deleting from Database
          {
              str = "Delete from eventdgv where Name='" + dataGridView1.Rows[j].Cells[1].Value.ToString() + "'";
              try
              {
                  using (SqlCeConnection cn = new SqlCeConnection(connection))
                  {
                      using (SqlCeCommand cmd = new SqlCeCommand(str, cn))
                      {
                          cn.Open();
                          cmd.ExecuteNonQuery();
                      }
                  }
              }
              catch (Exception ex)
              {
                  MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
              }

          }
          for (int s = dataGridView1.Rows.Count - 1; s >= 0; s--)// Deleting from gridview
          {
              if (Convert.ToBoolean(dataGridView1.Rows[s].Cells["Col1"].Value) == true)
              {
                  dataGridView1.Rows.RemoveAt(s);
              }
          }

          disp();
          MessageBox.Show("deleted succesfully");

      }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900