How to select multiple records from GridView and retrieve selected records value?

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

To select multiple records from the GridView and retrieve selected records, we can follow this approach.

Introduction

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.

To demonstrate this example, we are going to create a demo web page and my GridView code looks like below.

ASPX PAGE

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"

DataKeyNames="AutoId" OnPageIndexChanging="PaginateTheData" EnablePersistedSelection="true"

PageSize="5" PagerSettings-Mode="Numeric">

<Columns>

<asp:TemplateField HeaderText="Select">

<ItemTemplate>

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

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField HeaderText="AutoId" DataField="AutoId" />

<asp:BoundField HeaderText="First Name" DataField="FirstName" />

<asp:BoundField HeaderText="Last Name" DataField="LastName" />

<asp:TemplateField HeaderText="Is Active?">

<ItemTemplate>

<%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

<p><asp:Button ID="btnGetSelected" runat="server" Text="Get Selected Records" OnClick="GetSelectedRecords" /></p>

In the above code snippet, on the .aspx page we have a GridView with asp:BoundField & asp:TemplateField (this is used to display the column data in the format we want or is used to display custom data. In this case we have displayed a CheckBox as the first column and Yes/No as the last column based on Active column value from the database). We have set AutoId (primary key of the table) as the DataKeyNames that we will use to identify the selected row of the GridView.


CODE BEHIND

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

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

this.GetData();

}

}

/// <summary>

/// Paginates the data.

/// </summary>

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

/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewPageEventArgs"/>instance containing the event data.</param>

protected void PaginateTheData(object sender, GridViewPageEventArgs e)

{

GridView1.PageIndex = e.NewPageIndex;

this.GetData();

}


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, Active FROMPersonalDetail 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);

}

}

}

GridView1.DataSource = table;

GridView1.DataBind();

}


/// <summary>

/// Gets the selected records.

/// </summary>

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

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

protected void GetSelectedRecords(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)

{

// get the selected AutoId and cells text

Response.Write("AutoId: " + GridView1.DataKeys[row.RowIndex].Value + ", First Name: " + row.Cells[2].Text + "<br />");

}

}

}

The button fires GetSelectedRecords server side method, in which we have looped through all the rows of the GridView and found the CheckBox using FindControl method. In case the checkbox is checked by the user, we have retrieved the DataKey value of that row as well as the FirstName of that records (by retrieving 3rd cell text of that row).


Note: In this case, the selection is not maintained if user navigates to another page (this issue has been resolved in the next article, I will be publishing soon)

 

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)