2011-03-14 89 views
1

我有一個ContextMenuStrip用於DataGridView,DataGridView位於SplitContainer面板的內部。我的用戶請求他們能夠右鍵單擊網格中的任何行,然後右鍵單擊的行將成爲選定的行,並出現菜單。那我的代碼一直在努力,直到我把SplitContainer的面板更新CurrencyManager位置

private void DataGridView_MouseDown(object sender, MouseEventArgs e) 
    { 
     if (e.Button == MouseButtons.Right) 
     { 
      // Get the row that was right-clicked on 
      DataGridView.HitTestInfo hitTestInfo = DataGridView.HitTest(e.X, e.Y); 
      if (hitTestInfo != DataGridView.HitTestInfo.Nowhere) 
      { 
       // Change the binding source position to the new row to 'select' it 
       BindingSource.CurrencyManager.Position = hitTestInfo.RowIndex; 
      } 
     } 
    } 

一切內部在DataGridView似乎直到它到達最後一行

BindingSource.CurrencyManager.Position = hitTestInfo.RowIndex; 

中的位置始終保持在工作正常-1,即使hitTestInfo.RowIndex有一個不同的值,它正試圖分配。這可能是因爲SplitContainer面板?如果是這樣,關於如何解決它的任何建議?

感謝

回答

3

問題是你已經經歷的BindingContext(DataGridView的的)訪問的CurrencyManager以獲得正確的BindingManager的。我把你的源碼換成BindingSource.CurrencyManager(dataGridView1.BindingContext[dataGridView1.DataSource] as CurrencyManager),它就像一個魅力。以下是此更改的完整事件處理程序。我的DataGridView名稱是dataGridView1

private void dataGridView1_MouseDown(object sender, MouseEventArgs e) 
    { 
     if (e.Button == MouseButtons.Right)   
     {   
      // Get the row that was right-clicked on    
      DataGridView.HitTestInfo hitTestInfo = dataGridView1.HitTest(e.X, e.Y);    
      if (hitTestInfo != DataGridView.HitTestInfo.Nowhere)    
      {     
       // Change the binding source position to the new row to 'select' it     
       (dataGridView1.BindingContext[dataGridView1.DataSource] as CurrencyManager).Position = hitTestInfo.RowIndex;    
      }  
     } 
    }