How to select a GridView row and persist selection across different pages of the GridView

SheoNarayan
Posted by in ASP.NET category on for Beginner level | Points: 250 | Views : 20853 red flag
Rating: 4 out of 5  
 1 vote(s)

In this article, we shall learn how to select GridView rows and persist the selection during GridView pagination.

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 select a GridView record and persisit the selection across different pages of the GridView, we can follow this approach.

Below is my ASPX code.

ASPX PAGE

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

OnPageIndexChanging="PaginateTheData" PageSize="2" PagerSettings-Mode="Numeric"

SelectedRowStyle-BackColor="Yellow" AutoGenerateSelectButton="true" EnablePersistedSelection="true" />

<asp:Button ID="btnFind" runat="server" Text="Get Selected Record" OnClick="GetSelectedRecord" />


In the above code snippet, we have a GridView with pagination and AutoGenerateSelectButton=”true”
that generates the Select link column. Clicking the Select link selects the GridView row. After selecting a
record, by default when we move to another page, the selection is lost; so in order to persist the
selection while navigating to another pages, we can set the EnablePersistedSelection property to true. To uniquely identify each GridView row we have set DataKeyNames property of the GridView to the primary key of the database table from where we are getting the records.

CODE BEHIND

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

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

BindData();

}

}

/// <summary>

/// Binds the data.

/// </summary>

/// <returns></returns>

private void BindData()

{

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 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);

}

}

}

GridView1.DataSource = table;

GridView1.DataBind();

}

protected void PaginateTheData(object sender, GridViewPageEventArgs e)

{

GridView1.PageIndex = e.NewPageIndex;

this.BindData();

}

protected void GetSelectedRecord(object sender, EventArgs e)

{

var autoId = GridView1.SelectedDataKey.Value;

Response.Write("Selected record: " + autoId);

}

In the above code snippet, We get data from Database and attached to the GridView also we done the pagination for GridView data. To get the selected record, we need to access the SelectedDataKey property of the GridView. 

Notice that we have done that in the GetSelectedRecord method that fires on the click of the button. The output of the page in my case looks something similar to below image.


OUTPUT

In this case if we select a record in Page 3 and navigate to Page 4 and again come back to Page 3, previously selected record remains selected. Thanks to EnablePersistedSelection property of the GridView that has been introduced in latest version of ASP.NET. 

Hope this article would be useful for all. Keep reading forthcoming articles and do not forget to refer this to your friends. To read about my earlier articles on ASP.NET, click here.

Thanks for reading and do let me know your feedback for improvement if any.

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)