简体   繁体   中英

how to delete a row from the gridview by using a button outside the gridview

This seems like a repeated question but i'm not able to get my answer.

I have a grid view and I need to delete a particular row, when I click on a button outside the gridview.

 protected void btnDelete_Click(object sender, EventArgs e)
      {
            dtable = (DataTable)Session["data"];
            DataRow row = dtable.Rows[DataGV1.SelectedIndex];
            dtable.Rows.Remove(row);
            DataGV1.DataSource = dtable;
            DataGV1.DataBind();
            Session["data"] = dtable;
        }

The session variable has the previous state of datatable.

protected void DataGV1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        GridView _gridView = (GridView)sender;

        // Get the selected index 
         _selectedIndex = int.Parse(e.CommandArgument.ToString());
     }

Gridview controls

        onselectedindexchanged="DataGV1_SelectedIndexChanged" 
        OnRowCommand="DataGV1_RowCommand" OnRowDeleting="DataGV1_RowDeleting"
        AutoGenerateSelectButton="False" DataKeyNames="Role,Last_name">
        <Columns>
            <asp:ButtonField DataTextField="last_name" HeaderText="Last_name" CommandName="SingleClick"
                SortExpression="last_name" Text="Button" />
            <asp:BoundField DataField="role" HeaderText="role" SortExpression="role" />
             <asp:BoundField DataField="role" HeaderText="role"                      HeaderText="Frist_name" 
                 SortExpression="first_name" Text="First_name" />
        </Columns>
    </asp:GridView>

This doesn't seem to work. Can u please tell me where I am going wrong?

You have to store the _selectedIndex in a ViewState, and then on delete button click you retrieve the _selectedIndex from the Viewstate and use that to delete the row from your dataset, and reload the grid.

protected void DataGV1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        GridView _gridView = (GridView)sender;

        // Get the selected index 
         ViewState["SelIndex"] = e.CommandArgument.ToString();
     }

protected void btnDelete_Click(object sender, EventArgs e)

  {
        if(ViewState["SelIndex"] == null)
            return;

        int selIndex = int.Parse(ViewState["SelIndex"]);

        dtable = (DataTable)Session["data"];
        DataRow row = dtable.Rows[selIndex ];
        dtable.Rows.Remove(row);
        DataGV1.DataSource = dtable;
        DataGV1.DataBind();
        Session["data"] = dtable;
    }

If button is outside the GridView then no need to handle RowCommand event (In fact it is inappropriate).

Suggestion:

You have to add a TemplateField column, drop the CheckBox control in ItemTemplate of TemplateField and write code in click handler of button to traverse the GridView.Rows collection, identify the selected row by reading value of CheckBox control and perform deletion action if that CheckBox is checked.

Demo DataSource ( List<T> )

public class Item
{
    public int ID { get; set; }
    public string Name { get; set; }

    public static List<Item> Data()
    {
        List<Item> list = new List<Item>()
        {
                new Item(){ ID=11, Name="A"},
                new Item(){ ID=12, Name="B"},
                new Item(){ ID=13, Name="C"},
                new Item(){ ID=14, Name="D"},
                new Item(){ ID=15, Name="E"},
        };
        return list;
    }
}

Markup:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
   <Columns>
        <asp:ButtonField DataTextField="Name" HeaderText="Name" CommandName="SingleClick"
            SortExpression="last_name" Text="Button" />
        <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
    </Columns>
</asp:GridView>
<asp:Button ID="btnDelete" runat="server" Text="Button" />

Code-behind (Page_Load)

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Session["data"] = Item.Data();
        GridView1.DataSource = Session["data"];
        GridView1.DataBind();
    }
    /*--- RowCommand handler ---*/
    GridView1.RowCommand += (sa, ea) =>
        {
            ViewState["RowIndex"] = ea.CommandArgument.ToString();
        };
    /*--- Delete button click handler ---*/
    btnDelete.Click += (sa, ea) =>
        {
            if (ViewState["RowIndex"] != null)
            {
                int index = int.Parse(ViewState["RowIndex"].ToString());
                List<Item> items = Session["data"] as List<Item>;
                items.RemoveAt(index);
                GridView1.DataSource = Session["data"];
                GridView1.DataBind();
                ViewState["RowIndex"] = null;
            }
        };
}

take a look at these articles that would explain to delete a single/multiple rows from gridview. http://technico.qnownow.com/2012/06/15/how-to-delete-multiple-rows-from-gridview-with-checkboxes/ http://technico.qnownow.com/2012/06/14/how-to-delete-a-row-from-gridview-with-client-side-confirmation/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM