C# 基于唯一单元格值检索GridView行
我想根据单元格值检索网格视图行。例如,我的网格视图有4列(名称、m1、m2、m3),名称包含唯一值。因此,我想获得与指定名称对应的网格视图行C# 基于唯一单元格值检索GridView行,c#,.net,asp.net,gridview,filter,C#,.net,Asp.net,Gridview,Filter,我想根据单元格值检索网格视图行。例如,我的网格视图有4列(名称、m1、m2、m3),名称包含唯一值。因此,我想获得与指定名称对应的网格视图行 谢谢编辑:我意识到您可能指的是ASP.NET GridView而不是WinForm DataGridView,这正是我最初回答的问题。在这种情况下,方法是非常不同的 以防万一,我留下了下面的WinFormDataGridView方法 ASP.NET网格视图 GridView有些烦人,因为它不允许您按列名访问单元格。相反,你需要知道索引。您可以硬编码它,但这
谢谢编辑:我意识到您可能指的是ASP.NET GridView而不是WinForm DataGridView,这正是我最初回答的问题。在这种情况下,方法是非常不同的 以防万一,我留下了下面的WinFormDataGridView方法 ASP.NET网格视图 GridView有些烦人,因为它不允许您按列名访问单元格。相反,你需要知道索引。您可以硬编码它,但这是不可取的 硬编码方法:
string searchValue = "SpecifiedName";
// where 1 is the hardcoded cell index
var query = from GridViewRow row in GridView1.Rows
where row.Cells[1].Text == searchValue
select row;
GridViewRow result = query.FirstOrDefault();
string colName = "name";
int index = (from DataControlField col in GridView1.Columns
where col.HeaderText == colName
select GridView1.Columns.IndexOf(col)).FirstOrDefault();
// index used
var query = from GridViewRow row in GridView1.Rows
where row.Cells[index].Text == searchValue
select row;
GridViewRow result = query.FirstOrDefault();
动态方法(列索引查找):
string searchValue = "SpecifiedName";
// where 1 is the hardcoded cell index
var query = from GridViewRow row in GridView1.Rows
where row.Cells[1].Text == searchValue
select row;
GridViewRow result = query.FirstOrDefault();
string colName = "name";
int index = (from DataControlField col in GridView1.Columns
where col.HeaderText == colName
select GridView1.Columns.IndexOf(col)).FirstOrDefault();
// index used
var query = from GridViewRow row in GridView1.Rows
where row.Cells[index].Text == searchValue
select row;
GridViewRow result = query.FirstOrDefault();
备用索引查找:可以使用BoundField,而不是使用HeaderText
int index = (from DataControlField col in GridView1.Columns
where ((BoundField)col).DataField == colName
select GridView1.Columns.IndexOf(col)).FirstOrDefault();
WinFormDataGridView
把这个放在这里以防万一
string name = "SpecifiedName";
var query = from DataGridViewRow row in dataGridView1.Rows
where row.Cells["name"].Value.ToString() == name
select row;
// the row will be returned by this or contain a default value if not found
DataGridViewRow result = query.FirstOrDefault();
这就是DataKey属性的用途。So:GridView1.DataKeyNames=“name” 要找到您的匹配项:
foreach (GridViewRow gvr in GridView1.Rows)
{
if (GridView1.DataKeys[gvr.RowIndex].ToString().Equals("mymatch"))
{
GridView1.SelectedIndex = gvr.RowIndex;
break;
}
}
这样做需要更多的代码,但你明白了。现在,如果不想显示“名称”列,则不需要显示该列