2013-10-29 26 views
2

我用下面的代碼找到的DataGridView一行,並突出顯示該行。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的底部,用戶必須一直向下滾動到底部。我可以使用哪些代碼跳轉到我正在查找的行?任何幫助將非常感謝!

回答

4

我發現我可以使用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; 
} 
1
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如何使用 - 所選單元格必須是可見