通过键选择 GridView






4.60/5 (8投票s)
通过 DataKey 值以编程方式选择 GridView 中的一项。
引言
在使用声明式数据绑定时,有时会遇到需要以编程方式设置 GridView
控件选择项的情况。您可能会遇到的问题是,GridView
控件只能通过其行索引值来设置。通常,您只有键值。
本文演示了使用扩展方法,允许您使用 GridView
上的键值以编程方式设置 GridView
的选中值。
代码
在此示例中,下拉控件和 GridView
控件绑定到相同的数据源。当下拉控件更改时,会调用此行代码
GridView1.SetRowValueValueByKey(DropDownList1.SelectedValue);
这会调用 SetRowValueValueByKey
扩展方法,以设置 GridView
上的选中值。以下是代码隐藏文件的完整代码
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();
}
}
}
关注点
- 为此工作,您必须在
GridView
上设置DataValueField
。 - 当前,此代码不处理复合键;但是,可以对其进行修改以处理复合键。