Click here to Skip to main content
15,867,568 members
Articles / Desktop Programming / MFC
Tip/Trick

Fast Ensure Visible for CGridCtrl

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
5 Mar 2012CPOL 13.7K   1   3
This tip shows a very fast algorithm (with some constraints enforced for it to work) to EnsureVisible a row in CGridCtrl by Chris Maunder

Introduction



In one of my projects, I had to load around 200000 rows in the CGridCtrl and then had to provide the functionalitiy of EnsureVisible to scroll to and highlight a row. So I had to come up with a reasonably fast algorithm. 



The code



C++
// This function will only work if all the grid control rows are same in size

void GVEnsureVisible(CGridCtrl* pGridCtrl, int nRow)
{
	if(pGridCtrl== NULL)
		return;

	pGridCtrl->ResetScrollBars();

	int nItems = pGridCtrl->GetItemCount();

	int nPos = nRow;

	if(nItems > 0)
	{
		SCROLLINFO si;

		pGridCtrl->GetScrollInfo(SB_VERT, &si);

		double dx = (double)si.nMax / (double)nItems;

		si.cbSize = sizeof(SCROLLINFO);

		si.fMask = SIF_POS;

		si.nPos = (int)(dx * nPos) - si.nPage/2;

		pGridCtrl->SetScrollInfo(SB_VERT, &si, TRUE); 
		
	}

}




Points of Interest



This code will only work if all the rows of the Grid are of same size.



History



Article Uploaded : 5th March, 2012.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Kotha Technologies
Bangladesh Bangladesh
If you are not in - you are out !
- Chapter 1

Comments and Discussions

 
GeneralMy vote of 5 Pin
flute99924-Dec-19 19:42
flute99924-Dec-19 19:42 
QuestionCan you explain how this makes fast scroll? Also compare it with EnsureVisible, too. Pin
ehaerim24-Oct-13 9:56
ehaerim24-Oct-13 9:56 
AnswerRe: Can you explain how this makes fast scroll? Also compare it with EnsureVisible, too. Pin
Mukit, Ataul25-Oct-13 21:34
Mukit, Ataul25-Oct-13 21:34 
I used this code in one of my projects, I didn't add the method here.
It is only applicable for huge number of rows and they must be of same height. Then this will work very fast.

This technique just calculates the proper position of a row which needs to be set visible and then sets the scroll info which is basically two to three operations.

In the original codes of ensure visible, you have to iterate through a lot of rows and so it was slow. However, that code would work when the rows are of variable heights.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.