Technology: C# WinForm
Level: Expert
Depth: Medium
There are times that we display data in DataGridView or ListView. When the data flows beyond the size of the control, vertical scrollbar appears that we can use to navigate to positions of our choice. So good so far.
Now suppose that the data needs to be refreshed every 1 or 2 seconds. And we are viewing the bottom row or the bottom item, which means that the vertical scroll bar is at the bottom. Now, when the refresh method finishes execution, the data is repopulated and we notice that the vertical scroll bar jumps to the top. For constantly changing data with large number of rows or items, this poses a serious problem because the scrollbar is not locked to its position. Since the data refreshes very fast, dragging the scroll times 60 times a minute is also not plausible.
In this page, I put in my approach to counter the above problem. It’s simple and working.
The code goes like this:
public Form_ClosedPosition()
{
InitializeComponent();
for (int i = 0; i < 10; i++)
{
dataGridView_Closed.Rows.Add(i.ToString(), DateTime.Now.ToString(“HH:mm:ss”), i.ToString());
}
ReloadList();
}
private void ReloadList()
{
this.SuspendLayout();
dataGridView_Closed.SuspendLayout();
for (int i = 0; i < 10; i++)
{
dataGridView_Closed.Rows.Add(i.ToString(), DateTime.Now.ToString(“HH:mm:ss”), i.ToString());
}
for (int i = 0; i < 10; i++)
{
dataGridView_Closed.Rows.RemoveAt(0);
}
dataGridView_Closed.ResumeLayout(false);
this.ResumeLayout(false);
}
private void timer_Refresh_Tick(object sender, EventArgs e)
{
ReloadList();
}
What I am doing in the above code is appending the new rows and then removing the old rows from the beginning, instead of clearing the rows and then adding new rows. Doing the later, as we know, produce the flickering and jumping scroll bars as we have discussed intially.
The bottom line is: Don’t clear the rows and fill the control, instead, Append the new rows and remove the old ones.
Cheers and Cheese.
How to get vertical scroll bar in listview (.Net 2.0)? The items are added dynamically and when there are more items than display area, a new column is automatically created and horizontal scrollbar appears. Instead of that I want all items to come vertically only with a vertical scrollbar.
It’s true. There is no control in .Net 2.0 to my knowledge that does display the columns vertically. This article of mine is related to the scrollbars for the appending rows.
In case you come across the control as you said, please share