Taryn
Taryn

Reputation: 247680

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

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

Upvotes: 1

Views: 7550

Answers (1)

Sanjeevakumar Hiremath
Sanjeevakumar Hiremath

Reputation: 11263

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

Upvotes: 4

Related Questions