pinki
pinki

Reputation: 1418

Deleting a row in datagrid view

I want to Delete a row in the Gridview which is in the update panel . But instead of the command button ., i took a link button to get a confirmation message. Now if I press ok then the record should be deleted (both from db and frm girdview). I know how to delete from db but not when linkbutton is pressed, and deleting the record. And also the gridview is in update panel.so it should be reflected.

A sample code is appreciated.

Thanks

Upvotes: 0

Views: 1809

Answers (5)

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
        String productId = row.Cells[0].Text; // I suposed your product Id in very first column in gridview
        //Delete Code goes here..........
        ...........................
    }
}

Upvotes: 3

painotpi
painotpi

Reputation: 6996

I presume you have a method which sends a delete query.

Make a RowDeleting event handler, pass your row index using e.RowIndex to the delete method.

Use this e.RowIndex to write a query to delete the 'n'th row of your table. and then bind the data to your gridView.

Upvotes: 0

Mahesh KP
Mahesh KP

Reputation: 6446

bind the linkbutton id as the primary key. On client clicking the link button save that id in a hidden field. This hidden field value will be the id of row to be deleted.

Then on the server click of link button delete the row corresponding to the hidden field value

Upvotes: 0

Govind Malviya
Govind Malviya

Reputation: 13743

Set PK_ID to link button's command args like that

<asp:LinkButton runat="server" ID="btn_manage" Text="Delete" CommandArgument='<%#Eval("PK_ID") %>'
                                OnCommand="btn_manage_click">
</asp:LinkButton>

and access this PK_ID on event

protected void btn_manage_click(object sender, CommandEventArgs e)
{
    string ID = e.CommandArgument.ToString();

    //you delete code and gridview bind code
}

Upvotes: 0

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

you can use RowCommand event of gridview, like...

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {            
        e.CommandArgument  -- this return Data Key Value
//Deletion Code goes here.....
var brochureToDelete = (from b in dataContext.ArticleBrochures where b.ArticleId == ArticleId select b).FirstOrDefault(); 
if (brochureToDelete != null) 
{ 
dataContext.ArticleBrochures.DeleteOnSubmit(brochureToDelete);
dataContext.SubmitChanges(); 
bindBrochureGridView(ArticleId);
// if your gridview in updatepanel
//Call update method of UpdatePanel
//UpdatePanel.Update();
 }
}

Upvotes: 1

Related Questions