【问题标题】:Retrieve GridView row based on unique cell value根据唯一的单元格值检索 GridView 行
【发布时间】:2009-07-08 16:18:26
【问题描述】:

我想根据单元格值检索网格视图行。例如,我有一个包含 4 列(名称、m1、m2、m3)的网格视图,名称包含唯一值。所以,我想获取与指定名称对应的网格视图行。

谢谢

【问题讨论】:

    标签: c# .net asp.net gridview filter


    【解决方案1】:

    编辑:我意识到您可能指的是 ASP.NET GridView 而不是 WinForm DataGridView,这是我最初回答的问题。在这种情况下,方法非常不同。

    以防万一我在下面留下了 WinForm DataGridView 方法。

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

    备用索引查找:您可以使用 BoundField 代替 HeaderText。

    int index = (from DataControlField col in GridView1.Columns
                where ((BoundField)col).DataField == colName
                select GridView1.Columns.IndexOf(col)).FirstOrDefault();
    

    WinForm DataGridView

    把这个放在这里以防万一。

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

    【讨论】:

      【解决方案2】:

      这就是 DataKey 属性的用途。所以:GridView1.DataKeyNames="name"

      然后找到你的对手:

         foreach (GridViewRow gvr in GridView1.Rows)
          {
              if (GridView1.DataKeys[gvr.RowIndex].ToString().Equals("mymatch"))
              {
                  GridView1.SelectedIndex = gvr.RowIndex;
                  break;
              }
          }     
      

      然后需要更多代码来执行此操作,但您明白了。现在,如果您不想显示“名称”列,则无需显示。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-22
        • 2017-06-19
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 2011-12-31
        相关资源
        最近更新 更多