Introducing DotNetFunda.com on mobile http://m.dotnetfunda.com ! Be with DotNetFunda.com on the go !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 29936 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET > How to select all records (checkboxes for each record) from GridView in ASP.NET

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

3 vote(s)
Rating: 5 out of 5
Article posted by SheoNarayan on 10/1/2011 | Views: 7228 | Category: ASP.NET | Level: Intermediate | Points: 250 red flag


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.

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Microsoft_MVP] [Administrator]
Biography:Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001.

Connect me on Facebook | Twitter | LinkedIn | Blog

>> Write Response - Respond to this post and get points
Related Posts

Read ConnectionString Information from Application Configuration File.

This article describes how to change background colour of the whole item of a list view based on the search string

When we consume business objects in UI the logic can become pretty complex. Activities like setting the business object value, getting the object value and setting the user interface from the object value. We can minimize the complexity of UI interaction with business object using mediator pattern.

There are situations where we would like to detect if the post back is from a form interaction (i.e. submit or button clicks) or is it by hitting the browser F5 refresh button. Many of them will jump saying how about checking ‘Ispostback’ value. ‘IsPostback’ will always have the value which was set previously. So for instance if the page was posted back before refresh, then the value will be true and if the page is not posted back before refresh, then the value will be false.

Creating a SSRS Client Side Report is relatively easy by using dot net features without a need to use SSRS reporting service.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/28/2012 11:56:47 AM