Search code examples
c#asp.netlinkbutton

how to perform delete operation using link button or hyperlink or a href


i want to perform delete operation using a herf or LinkButton or HyperLink

<asp:LinkButton ID="lnkDelete" Text="Delete" runat="server" NavigateUrl='<%# Bind("ID","~/Persons.aspx?ID={0}") %>' OnClick="lnkDelete_Click" ></asp:LinkButton>

StoredProcedure:

CREATE PROCEDURE spDeletePerson
    @Id int
AS
BEGIN
    Delete from tblpersons where ID = @Id
    SET NOCOUNT ON;


END
GO

i want to stay on same page and to perform delete.


Solution

  • You must not set NavigateUrl - that'll take you to other page. Instead the code should look like:

    <asp:LinkButton CommandArgument='<%# Bind("ID") %>' ID="lnkDelete" 
      Text="Delete" runat="server" OnClick="lnkDelete_Click" />
    

    Notice the CommandArgument property - basically you can assign any custom string to this property and it will be passed to your OnClick handler (in this case we're passing there id).

    Code behind:

    protected void lnkDelete_Click(object sender, EventArgs e)
    {
      var button = (IButtonControl)sender;
      // grab the id from CommandArgument property
      int id = Convert.ToInt32(button.CommandArgument, CultureInfo.InvariantCulture);
      // call stored procedure based on id
    }