using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace UsingDataKeys
{
public partial class GridViewSelectionUsingDataKeys : System.Web.UI.Page
{
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
GridView1.SetRowValueValueByKey(DropDownList1.SelectedValue);
}
}
public static class GridViewExtensions
{
public static void SetRowValueValueByKey(this GridView GridView, string DataKeyValue)
{
int intSelectedIndex = 0;
int intPageIndex = 0;
int intGridViewPages = GridView.PageCount;
// Loop thru each page in the GridView
for (int intPage = 0; intPage < intGridViewPages; intPage++)
{
// Set the current GridView page
GridView.PageIndex = intPage;
// Bind the GridView to the current page
GridView.DataBind();
// Loop thru each DataKey in the GridView
for (int i = 0; i < GridView.DataKeys.Count; i++)
{
if (Convert.ToString(GridView.DataKeys[i].Value) == DataKeyValue)
{
// If it is a match set the variables and exit
intSelectedIndex = i;
intPageIndex = intPage;
break;
}
}
}
// Set the GridView to the values found
GridView.PageIndex = intPageIndex;
GridView.SelectedIndex = intSelectedIndex;
GridView.DataBind();
}
}
}