How to select all records (checkboxes for each record) from GridView in ASP.NET

SheoNarayan
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 20925 red flag
Rating: 5 out of 5  
 3 vote(s)

To select all records from the GridView using CheckBox, we can follow this approach.

GridView control is a powerful data grid control that allows us to display the data in tabular format with sorting and pagination. It also allows us to manipulate the data.

 

Get hundreds of ASP.NET Tips and Tricks and ASP.NET Online training here.

 

This article is one of the series of articles I am writing for last couple of days on GridView in ASP.NET. To select all records from the GridView using CheckBox, we can follow this approach.


ASPX PAGE

<asp:GridView runat="server" ID="GridView1" DataKeyNames="AutoId">

<Columns>

<asp:TemplateField HeaderText="Select">

<HeaderTemplate>

<asp:CheckBox ID="chkSelectAll" runat="server" onclick="SelectAll(this.id)" />

</HeaderTemplate>

<ItemTemplate>

<asp:CheckBox ID="chkSelect" runat="server" />

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>


<p>

<asp:Button ID="btnGet" runat="server" Text="Get Selected Records" OnClick="GetSelected" />

</p>


<script language="javascript" type="text/javascript">

function SelectAll(Id)

{

var myform = document.forms[0];

var len = myform.elements.length;


document.getElementById(Id).checked == true ? document.getElementById(Id).checked = false : document.getElementById(Id).checked = true;


for (var i = 0; i < len; i++)

{

if (myform.elements[i].type == 'checkbox')

{

if (myform.elements[i].checked)

{

myform.elements[i].checked = false;

}

else

{

myform.elements[i].checked = true;

}

}

}

}

</script>

In the above code snippet, we have a GridView with a column having a CheckBox for each record. The header of that column has a CheckBox. We want a functionality that checking the header checkbox should check all the checkboxes for the records automatically.

To achieve Select All functionality, we have specified a SelectAll() JavaScript function on click of the header checkbox. In this function, first we have retrieved the form and getting its element’s length. If the header checkbox is already checked then we are unchecking otherwise checking it. Then looping through all the elements of the form and checking for their type, if it is of “checkbox” type and not checked then checking it otherwise unchecking it.

CODE BEHIND

string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;


protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

GetData();

}

}


/// <summary>

/// Gets the selected.

/// </summary>

/// <param name="sender">The sender.</param>

/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>

protected void GetSelected(object sender, EventArgs e)

{

Response.Write("<h3>Selected records</h3>");

foreach (GridViewRow row in GridView1.Rows)

{

CheckBox chk = (CheckBox)row.FindControl("chkSelect");

if (chk.Checked)

{

Response.Write(GridView1.DataKeys[row.RowIndex].Value + ",");

}

}

}


private void GetData()

{

DataTable table = new DataTable();

// get the connection

using (SqlConnection conn = new SqlConnection(_connStr))

{

// write the sql statement to execute

string sql = "SELECT AutoId, FirstName, LastName, Age FROM PersonalDetail ORDER By AutoId";

// instantiate the command object to fire

using (SqlCommand cmd = new SqlCommand(sql, conn))

{

// get the adapter object and attach the command object to it

using (SqlDataAdapter ad = new SqlDataAdapter(cmd))

{

// fire Fill method to fetch the data and fill into DataTable

ad.Fill(table);

}

}

}

// specify the data source for the GridView

GridView1.DataSource = table;

// bind the data now

GridView1.DataBind();

}

 

In the Page_Load event, we are calling GetData() method that use ADO.NET to retrieve the data from the database and populated into the GridView.

On click of the “Get Selected Records” button, we have fired a GetSelected server side method that loops through all rows of the GridView and finds the first column checkbox, if they are checked, its DataKey value is written on the page.

My output of the page looks like below.

OUTPUT

Thanks for reading, hope you liked it.

Keep reading my forth coming articles. To read my series of articles on ASP.NET, click here.
Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)