1

I am trying to delete data from a gridview using a a link button. I need help with the logic and making the link button remove the row data from the database on click.

GridView

        <asp:GridView Style="width: 100%" ID="GvReportResults" runat="server"                       AutoGenerateColumns="False" EmptyDataText="No data" ShowHeaderWhenEmpty="True">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkBtnEdit" runat="server" CausesValidation="false" >Edit</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="LnkBtnRemove" runat="server" CausesValidation="false" CommandName="DeleteItem" CommandArgument='<%# Eval("OtherDataID") %>'>Delete</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="SourceID" HeaderText="ID" />
                <asp:BoundField DataField="LastName" HeaderText="Last Name" />
                <asp:BoundField DataField="FirstName" HeaderText="First Name" />
                <asp:BoundField DataField="MiddleName" HeaderText="Middle Name" />
                <asp:BoundField DataField="Title" HeaderText="Title" />
                <asp:BoundField DataField="NationalID" HeaderText="SSN" />
                <asp:BoundField DataField="DOB" HeaderText="DOB" />
                <asp:BoundField DataField="HireDate" HeaderText="Hire Date" />
                <asp:BoundField DataField="Address1" HeaderText="Address" />
                <asp:BoundField DataField="City" HeaderText="City" />
                <asp:BoundField DataField="State" HeaderText="State" />
                <asp:BoundField DataField="PostalCode" HeaderText="Zip Code" />
            </Columns>
        </asp:GridView>

Store precedure thats importing data to gridview

    private void BindGrid()
{
    //set up arguments for the stored proc
    int? FacilityID = (ddlFacility2.SelectedValue.Equals("-1")) ? (int?)null : int.Parse(ddlFacility2.SelectedValue);
    int? OtherDataID = null;

    //bind
    GvReportResults.DataSource = this.DataLayer.model.MS_spGetOtherData(FacilityID, OtherDataID);
    GvReportResults.DataBind();
}
1
  • You can Delete at RowCommand event by adding a command argurment at item template or using Gridview_RowDeleting event Refer this gives u basic idea satindersinght.blogspot.in/2012/08/… Commented May 28, 2013 at 5:45

3 Answers 3

1

Add OnClick attribute for the LinkButton, for example (added OnClick to your linkbutton code)

<asp:LinkButton ID="LnkBtnRemove" runat="server" CausesValidation="false" CommandName="DeleteItem" CommandArgument='<%# Eval("OtherDataID") %>' OnClick='LnkBtnRemove_Click'>Delete</asp:LinkButton>

Have OnClick listener as

protected void LnkBtnRemove_Click(object sender,EventArgs e)
{
   string id = ((LinkButton)sender).CommandArgument;//CommandArgument is always returns string
   Do_DeleteRow(id);//method to delete
   BindGrid();
}

private void Do_DeleteRow(string id)
{
   //your delete code will be added here
}
Sign up to request clarification or add additional context in comments.

2 Comments

Its erroring out on Do_DeleteRow(ID). Saying does not exist in current context?
Do_DeleteRow(ID) is a method that you have to define to delete. Sorry I haven't added that as comment. I will edit this...
0

Just attach ItemCommand event to your grid

On web page in your grid definition add:

<asp:DataGrid OnItemCommand="Grid_ItemCommand" />

after that in code behind:

void Grid_ItemCommand(Object sender, DataGridCommandEventArgs e)
{
    var id = Int32.Parse(e.CommandArgument.ToString()); //use parse if OtherDataID is int

    //here goes logic for deleting row
    this.DataLayer.model.spDeleteData(id);

    //after deleting rebind grid
    BindGrid();
}

7 Comments

How will adding a ItemCommand event to gridview make the link button delete the data? Sorry just confused as to where and what I put for the item command event. Thanks
Made some edits to make it more clear. On link button click that event will be fired with information about control clicked, command name and command argument. Just handle deleting there and you will be fine.
It is now giving an error on the "spDeleteData" in the this.DataLayer.model.spDeleteData(id); Saying my model does not contain a defination for deleteData. Also could you possibly show me how to place this event within the onclick event?
That is because it was just an example, you have to create in your model method to delete record from db.
Ok i got that done with a store precedure, Could you show example how to place this into the onclick function?
|
0

Convert your boundfiled into Item Template, Here using sourceid will fire delete Query.
Code look like this:

protected void GvReportResults_RowCommand(object sender, GridViewCommandEventArgs e)
 {
    if (e.CommandName == "DeleteItem")
    {
        int getrow = Convert.ToInt32(e.CommandArgument);
        Label lblSourceID = (Label)GvReportResults.Rows[getrow].FindControl("lblSourceID");
        bool flag=deleteRecord(lblSourceID.text);
        if(flag)
        {
         succes msg!
        }
         else{ failed msg}
        }
    }

    public bool deleteRecord(String SourceID)
    {
    try
       {
        SqlCommand cmd = new SqlCommand("Your Delete Query where condtion  ", conn);
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
        return true;
    }   
    catch(Exception ac)
    {
        return false;
    }

 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.