【问题标题】:DataGridView- How to jump to the selected row in search?DataGridView-如何跳转到搜索中的选定行?
【发布时间】:2013-11-08 01:20:55
【问题描述】:

我使用以下代码在 DataGridView 中查找一行并突出显示该行。

private void btnSearch_Click(object sender, EventArgs e)
    {
        currentMode = ModeSelection.Search;

        if (cmbSearchBy.SelectedIndex == Convert.ToInt16(SearchBy.MaterialID))
        {
            dgvSearchResults.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            int rowIndex = -1;
            try
            {
                foreach (DataGridViewRow row in dgvSearchResults.Rows)
                {
                    if (row.Cells[1].Value.ToString().Equals(materialLocation.MaterialID))
                    {
                        //Select the row here
                        rowIndex = row.Index;
                        dgvSearchResults.Rows[rowIndex].Selected = true;
                        break;
                    }
                }
            }
            catch (Exception ex) { throw ex; }
        }

完美运行。问题是我的 DataGridView 有超过 500 条记录,如果所选行靠近 DataGridView 的底部,用户必须一直向下滚动到底部。我可以使用哪个代码跳转到我要查找的行?任何帮助将不胜感激!

【问题讨论】:

    标签: c# winforms search gridview datagridview


    【解决方案1】:

    我发现我可以使用DataGridView.FirstDisplayedScrollingRowIndex 属性滚动到选定的行索引并将其显示为DataGridView 中的第一行。

    这就是我在我的程序中使用的方式-

    if (row.Cells[1].Value.ToString().Equals(materialLocation.MaterialID))
    {
        rowIndex = row.Index;
        dgvSearchResults.ClearSelection();                            
        dgvSearchResults.Rows[rowIndex].Selected = true;
        dgvSearchResults.FirstDisplayedScrollingRowIndex = rowIndex;
        dgvSearchResults.Focus();
        break;
    }
    

    【讨论】:

      【解决方案2】:
      int rowIndex = -1;
      foreach (DataGridViewRow row in dataGridView1.Rows)
      {
          if (row.Cells[0].Value.ToString().Equals(searchString))
          {
              rowIndex = row.Index;
              break;
          }
      }
      if (rowIndex >= 0)
      {
          dataGridView1.CurrentCell = dataGridView1[visibleColumnIndex, rowIndex];
      }
      

      visibleColumnIndex - 所选单元格必须可见

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-26
        • 2012-11-03
        • 2013-09-05
        • 2021-07-22
        • 2011-04-04
        相关资源
        最近更新 更多