更新CurrencyManager位置

时间:2011-03-14 18:02:41

标签: c# winforms bindingsource currencymanager

我在ContextMenuStrip上使用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;

即使hitTestInfo.RowIndex具有其尝试分配的不同值,“位置”始终保持为-1。这可能是因为SplitContainer面板?如果是的话,有关如何修复它的任何建议吗?

由于

1 个答案:

答案 0 :(得分: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;            
             }       
         }
    }