20/10/2014 by Nitesh

How To Get Multiple Selected Rows From GridView In ASP.Net


In my last post I explained how easily we can add a CheckBox column to a GridView in Asp.Net. Having a CheckBox column in GridView, now we can select multiple records from the GridView. We can now write some piece of code with the help of which we can perform multiple actions on the selected rows, like deleting the records, updating records etc. Continuing to the last post, today we will see how can we use these checkboxes to get selected rows from the GridView in a PostBack in ASP.Net and display them to the user for deletion.

We will use the same example we used in our last example where we have populated a GridView with 10 students. We will add a Delete button at the bottom of the GridView and handle the Button’s click event handler to get all selected rows of the GridView and display them to the user for confirmation.

Below is the complete code for ASPX page.


Below is the code written for the Delete button’s click handler. To understand the data bound to the GridView, please refer my previous article.

        protected void btnDelete_Click(object sender, EventArgs e)
            DataTable dt = new DataTable();

            foreach (GridViewRow item in grdData.Rows)
                if ((item.Cells[0].FindControl("cbSelect") as CheckBox).Checked)
                    DataRow dr = dt.NewRow();
                    dr["Id"] = item.Cells[1].Text;
                    dr["Name"] = item.Cells[2].Text;

            lblMsg.Visible = true;
            grdData.DataSource = dt;

Below are 2 screenshots showing the rows selected on 1st screen and then the selected rows in 2nd screen.


Hope you like this! Keep learning and sharing! Cheers!