Search code examples
c#datagridviewscrollbarpanel

How can i use datagridview scrollbar functionality in panel scrollbar in c#?


In my WinForm project I have panel control and it has DataGridview child. Datagridview has 50 columns and this needs scrolling. but i don't want to use Datagridview scroll bar. I want to use panel scroll bar. But these two scrollbar has different functionalities. Datagridview scrollbar has more capabilities than panel scroll bar.

For example,

1)With DatagirdView scrollbar you can freeze columns easily.

2)Also while entering data in datagridview, with TAB key, scrollbars move automatically.

Is there any solution to add Datagridview scroll bar functions to panel scrollbar's.

Or How to add the above 2 functions to panel scrollbar.

Thanx in advance.


Solution

  • The panel scrollbar can only be used to control the position of the entire datagridview.

    Here is a workaround that using external Scrollbar to scroll datagridview.

    First, need to add a HScrollBar to the form and set its properties as followed.

    hScrollBar1.Maximum = dataGridView1.Columns[0].Width * dataGridView1.ColumnCount + dataGridView1.RowHeadersWidth;
    hScrollBar1.Value = 0;
    hScrollBar1.Location = new Point(panel1.Location.X, panel1.Location.Y + panel1.Height);
    

    And subscribe to Scroll event

    hScrollBar1.Scroll += hScrollBar_Scroll;
    
    private void hScrollBar_Scroll(object sender, ScrollEventArgs e)
    {
        int rowindex = dataGridView1.CurrentCell.RowIndex;
        int columnindex = (hScrollBar1.Value - dataGridView1.RowHeadersWidth) / dataGridView1.Columns[0].Width;
        this.dataGridView1.CurrentCell = this.dataGridView1[columnindex, rowindex];
    }
    

    If want to change the scrollbar value according to the selected cell, subscribe to DataGridView.SelectionChanged event.

    dataGridView1.SelectionChanged += dataGridView_SelectionChanged;
    
    private void dataGridView1_SelectionChanged(object sender, EventArgs e)
    {
        hScrollBar1.Value = (dataGridView1.CurrentCell.ColumnIndex + 1) * dataGridView1.Columns[0].Width + dataGridView1.RowHeadersWidth;
    }
    

    The above columnindex and hScrollBar1.Value are obtained according to the following formula:

    enter image description here