Montag, 20. November 2006

The DatagridView readonly performance Control

In my current project, a winform application which searches addresses around different databases, i use the datagridview control
to display the found addresses.

I don't know how much results i get because that depends on the search criteria the user enters.

Already at results with a count of 1000 entries the performance of the grid is bad.
For example, if i sort the datasource with the click on one of the columns it needs 20-30 seconds.
Thats not really acceptable.

So i searched a little bit around and found cool results in dependency to the "virtual mode" property.

If you bind data to the datagrid with virtual mode set to true the datagrid asks for the data that should be displayed,
and ONLY that data.
Behind the scenes i have a datatable which holds my search results.
The "ask for data" is an event called "CellValueNeeded" and gives me an cell- and a rowindex.
Easy with the datatable.
Sorting is even more easy: call the datatable.DefaultView.Sort property and you're done.

CODE START

//binding the data
//this causes the datagridview to raise the CellValueNeeded Event
dataGridView1.VirtualMode = true;
dataGridView1.RowCount = currentDataView.Table.Rows.Count;

//CellValueNeeded Event
DataRow needeRow = currentDataView[e.RowIndex].Row;
if (needeRow != null && needeRow[e.ColumnIndex] != null)
e.Value = needeRow[e.ColumnIndex];
else
e.Value = System.DBNull.Value;

//Sorting
currentDataView.Sort = string.Format("[{0}] {1}", currentSortColumn, sortOrder);

CODE END

And the performance is amazing: click and get immediately results. very cool...

Summary: If you have more or an unknown amount of data to display, use the virtual mode.
You have to sort manually, set the sortglyph to the column you are sorting and give the datagridview the data it needs.
in my case i have a readonly datagrid, for editmodes enabled you have to do a little bit more :)

Some links to articles about it:

Presenting Data with the DataGridView Control in .NET 2.0
http://www.awprofessional.com/articles/article.asp?p=446453&seqNum=1&rl=1

Virtual Mode in the Windows Forms DataGridView Control
http://msdn2.microsoft.com/en-us/library/ms171622(VS.80).aspx

How to: Implement Virtual Mode in the Windows Forms DataGridView Control
http://msdn2.microsoft.com/en-us/library/2b177d6d.aspx

happy displaying ...

tingle

Keine Kommentare: