Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Any sample code how to delete record in gridview by click on the "delete" button?
Posted

use template field and pass id as CommandArgument

C#
<asp:templatefield xmlns:asp="#unknown">
                 <itemtemplate>
                 <asp:linkbutton id="lb1" runat="server" causesvalidation="false" onclientclick="return confirm('Are You sure to delete this entry')" text="Delete" commandargument="<%#Eval("id")%>"></asp:linkbutton>
                 </itemtemplate>
                 
                 </asp:templatefield>


and on row command of gridview
C#
protected void rowcmd(object sender, GridViewCommandEventArgs e)
   {
     // create and open DB connection
       try
       {
           //int index = Convert.ToInt32(e.CommandArgument);
           //GridViewRow row = GridView1.Rows[index];
           Int32 id = Convert.ToInt32(e.CommandArgument);
           string comm = "Delete from tblComments where id=@id";
           SqlCommand cmd = new SqlCommand(comm, Db.GetConnection());
           cmd.Parameters.AddWithValue("id", id);
           cmd.ExecuteNonQuery();
           //ClientScript.RegisterStartupScript
           //(GetType(), "Javascript", "javascript: return alert('Deleted');; ", true);
           GridView1.DataBind();
       }
       catch (Exception ex)
       {
       }

   }
 
Share this answer
 
Comments
HL22 10-Jan-12 7:43am    
do u hv coding on vb.net?
hello dear,

in your gridview , when you click on the delete button (if i.e. auto generated column) get the id of that row means unique id of that row.
If there is no unique id then bind it in hidden field. and get that id on the click event of delete button. and execute delete query. like this :
C#
string str = GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();
SqlCommand cmd = new SqlCommand("delete from tablename where id=@id", con);
cmd.Parameters.AddWithValue("@id", str);
con.Open();
cmd.ExecuteNonQuery();
con.Close();


and bind grid again.

Hope this will help you.
And Don't forget to mark as answer if it helps. :)
 
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