Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the selected range in the .Net WinForms Chart Control?

I'm using the C# built-in Winforms Chart control (System.Windows.Forms.DataVisualization.Charting.Chart) with its built-in ability to let the user select a range. What I'd like to do is to read back what range the user has selected. Surely there must be some easy way to do this, but I haven't been able to find it.

The cursor is enabled like so:

var ca = chart1.ChartAreas["ChartArea1"].CursorX;
ca.CursorX.IsUserEnabled = true;
ca.CursorX.IsUserSelectionEnabled = true;

I am aware that I can make the chart zoom when the user selects a range by enabling ca.AxisX.ScaleView.Zoomable, but I don't want the picture to change: instead I am using the chart as a way to display information and let the user select a range of X values for which I then do some extra processing.

I tried hooking to chart1.SelectionRangeChanged and that indeed fires every time the range is changed - I just can't seem to get the selection range from the CursorEventArg I get back. It has "NewSelectionStart" and "NewSelectionEnd" fields, but those are NaN, disappointingly. I tried looking at the various properties of the chart and the axes, but didn't find anything that sounded promising.

Further investigation reveals the ChartArea.CursorX.SelectionStart property which sounds like exactly what I need... except that it's NaN too. I don't know whether this is normal or I'm hitting some sort of bug?

So, how can I figure out what range the user selected?

like image 561
redtuna Avatar asked Apr 03 '13 00:04

redtuna


1 Answers

OK, well, I figured it out. Here's the scoop:

There's a SelectionRangeChang*ing* event, and when that one runs the ChartArea.CursorX.SelectionStart and ChartArea.CursorX.SelectionEnd fields have correct values in them. But the user hasn't released the mouse button yet, so you should just store them.

When the user releases the mouse button, the SelectionRangeChang*ed* event fires. Somehow it's designed in such a way that SelectionStart and SelectionEnd are reset to NaN (just like the NewSelectionStart and NewSelectionEnd fields in the event parameters). What you have to do is to use the values that you squirreled away from the other event handler now that you know the time is right to use them.

So there you have it! Hopefully this answer will save someone else from wasting time.

like image 125
redtuna Avatar answered Oct 02 '22 15:10

redtuna