1

我有一个ContextMenuStrip用于 a 的DataGridView,DataGridView 在SplitContainer面板内。我的用户要求他们能够右键单击网格中的任何行,然后他们右键单击的行将成为选定的行并出现菜单。我一直在工作的代码,直到我将 DataGridView 放在 SplitContainer 面板内

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;
            }
        }
    }

一切似乎都工作正常,直到它到达最后一行

BindingSource.CurrencyManager.Position = hitTestInfo.RowIndex;

Position 始终保持在 -1,即使hitTestInfo.RowIndex它尝试分配的值不同。这可能是因为 SplitContainer 面板吗?如果是这样,有关如何解决它的任何建议?

谢谢

4

1 回答 1

4

问题是您必须通过(DataGridView 的)BindingContext 访问 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;            
             }       
         }
    }
于 2011-03-14T18:20:22.753 回答