开发者

Update CurrencyManager Position

I have a ContextMenuStrip that is used on a DataGridView, the DataGridView is inside of a SplitContainer panel. My users have requested that they be able to right click on any of the rows in the grid and the row they right-click on will then become the selected row and the menu will appear. The code that I have has been working, until I placed the DataGridView inside of the SplitContainer Panel

private void DataGridView_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            // Get the row that was right-clicked on
            DataGridView.HitTestInfo hitTestInfo = DataG开发者_Python百科ridView.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;
            }
        }
    }

Everything seems to be working fine until it reaches the last line

BindingSource.CurrencyManager.Position = hitTestInfo.RowIndex;

The Position always stays at -1, even if the hitTestInfo.RowIndex has a different value it is trying to assign. Could this be because of the SplitContainer Panel? If so, any suggestions on how to fix it?

Thanks


The problem is you've to access the CurrencyManager through BindingContext (of DataGridView) to get the correct BindingManager. I took your source code just replaced BindingSource.CurrencyManager with (dataGridView1.BindingContext[dataGridView1.DataSource] as CurrencyManager) and it works like a charm. Following is the full event handler with this change. My DataGridView name is 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;            
             }       
         }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜