Click here to Skip to main content
Click here to Skip to main content

Using the MS Chart control in VC++

By , 14 Jun 2003
 

Introduction

The following is the description for using the MS Chart control in VC++. The diagram below will give you an idea of the chart we are going to make.

First insert the chart control in your project using Project->Add Reference->Microsoft Chart Control. Next is populating the chart control. When I was working with Visual Basic I had used a data source to pass data to the chart. But in VC++ ,I did not get the datasource method in the initial tries. So I passed the chart data through a COleSafeArray. Thanks to J L Colson for illuminating the details in his article on code project.

Here is the code snippet for that.

//First create a safe array
COleSafeArray saRet;

SAFEARRAYBOUND sab[2];

sab[0].cElements =noOfRows; // give this exactly the number of rows you
                               display in your chart
sab[1].cElements = 5;       // number of columns + 1 (because the first
                            // column is where we put the row labels,
                            // ie in 1.1, 2.1, 3.1, 4,1 etc

sab[0].lLbound = sab[1].lLbound = 1;

// Use the chart as the backdrop of the legend.
m_ChartControl.SetShowLegend(TRUE);

// Create the safe-array...

saRet.Create(VT_BSTR, 2, sab);

long index[2] = { 0, 0 };   //a 2D graph needs a 2D array as index array
BSTR bstr;
index[0] = 1;
  
FILEDETAILS filedetailsstruct; // this is just a datastructure I used,
                               // pls see attached code
CString cstemp;

// m_filedetails is an STL list of filedetailsstruct
// in this loop we populate the safe array
for (i = m_filedetails.begin(); i != m_filedetails.end(); i++)
{
    filedetailsstruct = (FILEDETAILS *) i;
    index[1] = 1;

    // make sure this cannot be converted to a valid number like "54" and
    // is a valid string like "John"
    bstr = filedetailsstruct.login.AllocSysString(); // Row label
    saRet.PutElement(index, bstr);

    index[1] = 2;
    bstr = filedetailsstruct.n9000.AllocSysString(); // Data for column 1
    ::SysFreeString(bstr);
    saRet.PutElement(index, bstr);
  
    index[1] = 3;
      bstr = filedetailsstruct.n9002.AllocSysString(); // Data for column 2
    ::SysFreeString(bstr);
    saRet.PutElement(index, bstr);
  
    index[1] = 4;
    bstr = filedetailsstruct.n9004.AllocSysString(); // Data for column 3
    ::SysFreeString(bstr);
    saRet.PutElement(index, bstr);

    index[1] = 5;
    bstr = filedetailsstruct.nCancel.AllocSysString();// Data for column 4
    ::SysFreeString(bstr);
    saRet.PutElement(index, bstr);

    index[0]++;
}

//now hand over the safe array to the chart control
m_ChartControl.SetChartData(saRet.Detach());

Our chart data will look like this:

2,1  2,2  2,3  2,4  2,5
1,1  1,2  1,3  1,4  1,5

where 1,1 - Row label 1 2,1 - Row Label 2

Okay now to label the columns:

m_ChartControl.SetColumnLabelCount(4);
m_ChartControl.SetColumn(1);
m_ChartControl.SetColumnLabel("Monday");
m_ChartControl.SetColumn(2);
m_ChartControl.SetColumnLabel("Wednesday");
m_ChartControl.SetColumn(3);
m_ChartControl.SetColumnLabel("Friday");
m_ChartControl.SetColumn(4);
m_ChartControl.SetColumnLabel("Saturday");

Thats it folks.

Dependencies

MFC42.DLL, MSVCRT.DLL, KERNEL32.DLL, USER32.DLL, ADVAPI32.DLL, OLEAUT32.DLL

Developed On Windows 2000 Server using VC++ ver 6

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Alex C. Punnen
Architect
India India
Member
Hi everyone!! Sometimes I get real stumped with some concepts and that gets me excited.So I say - hey let me explore - and there I go!! .Currently I am working as software engineer for Nokia Siemens Networks, Bangalore -India.My dream subject - Physics!!

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMore samplememberAnkata10 Jun '09 - 14:04 
Dear Alex,
 
That is a good article. I am using VC++ and I want to use this control. Could you please to give me more sample about this control (pie chart, bar chart). Or do you know any link concerned?
 
Thanks
 
あんかた

GeneralMay i Have this in C#memberIrfan Kothari29 Dec '06 - 20:12 
Hi friends,
 
Has anybody done it in C#
i want this chart controls example in c#
 
any kind of help is appreciable
thanks in advance
 
irfan kothari
 
"Take Care Not Chances"

GeneralRe: May i Have this in C#memberemadns26 Aug '08 - 6:43 
If I want to do it in C# I prefer using ZedGraph
 
http://www.codeproject.com/KB/graphics/zedgraph.aspx
QuestionHow to add only one vertical grid line in the plot? [modified]memberYoun-seong Cho28 Nov '06 - 19:40 
x-Axis's range are 0 ~ 100.
y-Axis's range are 0 ~ 300.
 
I wnat to add only one vertical grid line at x=25 in the plot
It must parallel line for y-Axis.
How can I code?
 

 
-- modified at 2:00 Wednesday 29th November, 2006
Questiondependencies?memberdkvp10 Oct '06 - 23:23 
I have used the ms chart control and it is perfectly working in a VC++ installed machine (XP). But when i take the executable to another machine where VC++ is not installed it doesnt work! I have MSCHRT20.OCX copied to system folder. What else i require? Any help is appreciated
AnswerRe: dependencies?memberAnanth.tm2 Nov '06 - 17:07 
I'm having the same problem, you need to "regsvr32 mschrt20.ocx" to register the control.
But it appears this is not enough, I'm trying to break my head to make it work, will let you know if I find it
GeneralRe: dependencies?memberAnanth.tm3 Nov '06 - 8:55 
okay, solved it Smile | :)
1) copy mschrt20.ocx to your Release\Debug folder. You have to deploy this along with your executables, add it as part of your executables.
2) In PostBuild setup or somewhere else register the chart control (regsvr32 mschrt20.ocx)
3) You need a license key for registering the ActiveX control (see MSDN on why you need license key)
4) Run M$ Licence Key REquester to get license key for MSChart (http://support.microsoft.com/kb/151771)
5) Hard-code your license key in your file.
6) convert the WCHAR to BSTR as explained in the MSDN article
7) Create your MSChart control passing the license key:
so code will look something like this:
WCHAR pwchLicenseKey[] =
{
0x0038, 0x0045, 0x0031, 0x0034, 0x0037, 0x0043,
0x0036, 0x0039, 0x002D, 0x0042, 0x0044, 0x0035,
0x0030, 0x002D, 0x0031, 0x0031, 0x0064, 0x0031,
0x002D, 0x0042, 0x0031, 0x0033, 0x0037, 0x002D,
0x0030, 0x0030, 0x0030, 0x0030, 0x0046, 0x0038,
0x0037, 0x0035, 0x0033, 0x0046, 0x0035, 0x0044,
};
 
BSTR bstrLicenseKey = ::SysAllocStringLen(pwchLicenseKey,
sizeof(pwchLicenseKey)/sizeof(WCHAR));
 
m_Chart.CreateControl(
m_Chart.GetClsid(), //REFCLSID clsid,
_T("MSChart20Lib.MSChart.2"), // LPCTSTR pszWindowName,
WS_DISABLED, // DWORD dwStyle,
CRect(0,0,100,100), // const RECT& rect
this, // CWnd* pParentWnd
IDC_MY_CHART_CTRL_ID, // UINT nID
NULL, // CFile* pPersist = NULL,
FALSE, // BOOL bStorage = FALSE,
bstrLicenseKey ); // BSTR bstrLicKey = NULL
 
::SysFreeString(bstrLicenseKey);
 
8) presto, it works Smile | :)

GeneralMSChart control display problem!!membershinyhui13 Jul '06 - 20:59 
Is it MSChart control have the maximum value to display? I have a chart control which display data from a date to a date from selection of date time picker... if my selection in a short period the mschart work well but the date period too long it appear a application error "Debug Assertion Failed"
so i wonder is it there got a maximum value on that or something wrong with my program...
Please advice!!


GeneralRe: MSChart control display problem!!memberAnanth.tm2 Nov '06 - 17:38 
If you use SetColumnCount(10) and one of the data for a particular row is say 12, it crashes. Do not set RowCount or ColumnCount if that's your problem
QuestionCustom Text Over Bars??memberchris17531 Mar '06 - 2:47 
have been working with the Active X MSCharting class for about a week or so and I have come up with the issue of putting custom labels within the chart. I am using Microsoft Visual Studio 6.0 on Windows 2000 SP4. So far this is what I have found....
 
CVcSeriesCollection sc = m_chart.GetPlot().GetSeriesCollection();
// 2 will select the second series.
CVcSeries s = sc.GetItem(2);
CVcDataPoints dps = s.GetDataPoints();
// -1 will select all the datapoints in the series
CVcDataPoint dp = dps.GetItem(-1);
// 1 = VtChLabelLocationTypeAbovePoint which places the values ontop the bars.
dp.GetDataPointLabel().SetLocationType(1);
This works perfectly for displaying the values of all the datapoints above the bars in a selected series.
 
Now the Problem
I would like to put a custom label on top a datapoint like "8 hours". I have tried the following but get an error when calling dps.GetItem(1);
 
CVcSeriesCollection sc = m_chart.GetPlot().GetSeriesCollection();
CVcSeries s = sc.GetItem(2);
CVcDataPoints dps = s.GetDataPoints();
long l_Item_Count = dps.GetCount();
CVcDataPoint dp = dps.GetItem(1);
dp.GetDataPointLabel().SetLocationType(1);
dp.GetDataPointLabel().SetText("8 Hours");
 
Other Information
- There is a dp.GetDataPointLabel().SetCustom(bool) function but I have no idea how to use it. I can set this function to true after calling dps.GetItem(-1) but it seems to do nothing.
- The error that I get says "Index given is out of bounds" but the value that gets stored into l_Item_count is 5.
- This is how I am adding data to the chart. m_chart.GetDataGrid().SetData(ROW_NUM,COL_NUM,d_va lue,0); which I am pretty sure is correct.
- This is what is in my Visual Studios Output box after the exception is thrown..."First-chance exception in Testd.exe (KERNEL32.DLL): 0xE06D7363: Microsoft C++ Exception. Warning: Uncaught exception in WindowProc (returning 1)."
- I am not adding or modifing the columns or rows in the bar chart at all. I am just using the 5 generic rows and 4 generic columns built by the chart class.
- I can change the labels with the following function: m_chart.GetDataGrid().SetRowLabel(ROW_NUM,1,"RowA" );. The 1 is an index which does something but I dont know what. I have tried to set this value to 2 and 3 but I get errors. This may play a part in this problem I dont really know.
 

 
Thanks for taking the time to read my problem. Please responed with any information.
Thanks again.

 
Chris
Generaltext over barsmembermarcdev2 Aug '05 - 4:50 
How can I add the row value over or above the bar/colum?
 
Marc Soleda.
 
... she said you are the perfect stranger she said baby let's keep it like this... Tunnel of Love, Dire Straits.
AnswerRe: text over barsmemberchris17531 Mar '06 - 2:43 
Yes you can add the row value over the bars try this...
 
CVcSeriesCollection sc = m_chart.GetPlot().GetSeriesCollection();
CVcSeries s = sc.GetItem(2); // Second Series
CVcDataPoints dps = s.GetDataPoints();
long here = dps.GetCount();
CVcDataPoint dp = dps.GetItem(-1); // All data points within the series
dp.GetDataPointLabel().SetLocationType(1); //1 = Above datapoints.

 
Chris
Generalbar colorsmembermarcdev19 Jul '05 - 22:18 
I'm working with MSChart to build a column/bar chart and I want to change programatically the colors of each column. How can I do that?
I've tried to do it by changing the color of the pen but it doesn't change at all:
 
m_msChart.GetPlot().GetSeriesCollection().GetItem(1).GetPen().GetVtColor().Set(0, 255, 0);
 
What's wrong or what method do I have to use?
 
Thanks,
Marc Soleda
 
... she said you are the perfect stranger she said baby let's keep it like this... Tunnel of Love, Dire Straits.
GeneralRe: bar colorsmembermarcdev20 Jul '05 - 5:32 
Oops! I finally found it by myself. If someone else needed is:
 
m_msChart.GetPlot().GetSeriesCollection().GetItem(1).GetDataPoints().GetItem(-1).GetBrush().GetFillColor().Set(0, 0, 255);
 
Bye,
Marc Soleda
 
... she said you are the perfect stranger she said baby let's keep it like this... Tunnel of Love, Dire Straits.
GeneralRe: bar colorsmemberchris17531 Mar '06 - 2:52 
Try calling the following before attempting to change the series color.
m_chart.GetPlot().GetBackdrop().GetFill().SetStyle(1); 

 
Chris
Generalflickering problemmembersayup30 Jun '05 - 20:47 
hello,
I also want to know the solution for flickering of chart when chart is refreshed.(this is not in reference to my query about dialog application coz for this i just changed the data in the demo proj only)
thanks
 
sayup
Generaladding resource file of thew controlmembersayup30 Jun '05 - 20:43 
hello,
I have been trying to use the activex control.I created a simple dialog base application and i want to use the activex controls in my application.what is the exact procedure?do we first have to include the resource file of the controland then declare the ID of the resource file in our dialog application?
please reply urgently
I need the stepe wise procedure to include the controlin my dialog application
thanks
 

 

 
sayup
Generalsimple plotting of x,y valuesmemberKrishna Seetharaman6 Mar '05 - 19:14 

Hi All,
I am starting to use the MS chart control in C++ for displaying a x-y plotter graph. But i am not able to figure out how to display a set of 32(x,y) values which range from 0-360 degrees. Could you please help me out? Also is there any help for using mschart in vc++?
 
Awaiting your reply.
 
Thanks,
Krishna.
QuestionHow import Ms Chart to my project?membermw81120 Feb '05 - 21:08 
How import Ms Chart to my project?
 
ss
AnswerRe: How import Ms Chart to my project?memberKrishna Seetharaman6 Mar '05 - 19:18 

Hi mw811,
I am starting to use the MS chart control in C++ for displaying a x-y plotter graph. But i am not able to figure out how to display a set of 32(x,y) values which range from 0-360 degrees. Could you please help me out? Also is there any help for using mschart in vc++?
 
Awaiting your reply.
 
Thanks,
Krishna.
GeneralRe: How import Ms Chart to my project?membermw8117 Mar '05 - 19:44 
I never use MS Chart, I must Chart atypical.
I draw on Static Img and create chart.
I queston this forum because look ideal(perfect) chart and simple.
 

Sorry for my english Smile | :) I learn hard.
 
mw811.
 
ss
QuestionHow to hide grid line in the plotmembervinubhai26 Apr '04 - 2:19 
How to hide grid lines in the plot
 
Vinod Tanaji patil
AnswerRe: How to hide grid line in the plotmemberbrngupta2 Nov '04 - 20:40 
Goto "AxisGrid" tab, and, for each of the Axis combo option, select the Style as "NULL" from MajorGridlines/MiniorGridlines. THATS IT.
GeneralRe: How to hide grid line in the plotmemberAnanth.tm13 Oct '06 - 9:01 
or dynamically:
 
int ChartXAxis = 0;
_variant_t varIndex((long) 0);
CVcAxis xAxis(m_Chart.GetPlot().GetAxis(ChartXAxis, varIndex ));
 
//Remove GridLines
xAxis.GetAxisGrid().GetMajorPen().SetStyle(0);
xAxis.GetAxisGrid().GetMinorPen().SetStyle(0);
yAxis.GetAxisGrid().GetMajorPen().SetStyle(0); //not able to "off" this gridline, why?
yAxis.GetAxisGrid().GetMinorPen().SetStyle(0);
QuestionUse MS Chart Control for free?membermarathom23 Apr '04 - 3:32 
Hi,
 
is the MS Chart Control free to use? Can I integrate it in a commercial software without licence costs?
 
Thanks for any information,
 
Tom
AnswerRe: Use MS Chart Control for free?memberbrngupta2 Nov '04 - 20:33 
Yes, it is FREE.
 
You can do, whatevery you want.
Generalit's a hagmembertimepalette19 Feb '04 - 22:51 
Too Many classes...
GeneralRe: it's a hagmemberbrngupta2 Nov '04 - 20:36 
CMSFlexGrid is the main class, you use mostly.
Others are required, if you want to manipulate the smaller parts of the graph, otherwise, hou can just neglect them.
Generalcolors of the GraphsmemberVasudevacharyulu27 Aug '03 - 1:56 
How to define the Colors of the Graphs? I would like to define the colors.
GeneralRe: colors of the Graphsmemberbrngupta2 Nov '04 - 20:44 
If you are talking about changing the line colors, you can do that, from the "Series Color" tab.
GeneralRe: colors of the Graphsmemberchris17531 Mar '06 - 2:50 
This is possible to do it within the program itself. Here is a sample of how to change the background color of the graph...
m_chart.GetPlot().GetBackdrop().GetFill().SetStyle(1); 
m_chart.GetPlot().GetBackdrop().GetFill().GetBrush().GetFillColor().Set(10, 10, 10); 

 
Chris
GeneralX and Y labels; Zoommemberdjteambse6 Aug '03 - 0:20 
Hi,
how can I add an x and y label in an MsChart control? I can't find a solution to that anywhere. Also does anybody know how to implement some sort of zooming function?
 
Perhaps somebody can help me as well by telling me where to find a reasonably good help file for the MSChart control when used with Visual C++. I can only find a help file for Visual Basic.
Thanks.

GeneralRe: X and Y labels; ZoommemberKrishna Seetharaman6 Mar '05 - 19:12 
Hi djteambse,
I am starting to use the MS chart control in C++ for displaying a x-y plotter graph. But i am not able to figure out how to display a set of 32(x,y) values which range from 0-360 degrees. Could you please help me out? Also is there any help for using mschart in vc++?
 
Awaiting your reply.
 
Thanks,
Krishna.
GeneralRe: X and Y labels; ZoommemberAnanth.tm13 Oct '06 - 9:05 
3 years late reply, but still....might come in handy for someone else
no proper help file for VC++ consumption, you have to stumble, google and make your way
 
Addin x & y label:
 
_variant_t varIndex((long) 0);
CVcAxis xAxis(m_Chart.GetPlot().GetAxis(0, varIndex ));
CVcAxisTitle xAxisTitle(xAxis.GetAxisTitle());
xAxisTitle.SetVisible(true);
//spruce up title
xAxisTitle.GetVtFont().SetStyle( e_ChartFontStyleBold );
CString strRowTitle = _T("XTitle");
xAxisTitle.SetText(strRowTitle);
 

//Set Y-axis Title
CVcAxis yAxis( m_Chart.GetPlot().GetAxis( 1, varIndex ) );
CVcAxisTitle yAxisTitle( yAxis.GetAxisTitle() );
yAxisTitle.SetVisible( true );
//spruce up title
yAxisTitle.GetVtFont().SetStyle( e_ChartFontStyleBold );
CString strColumnTitle = _T("YTitle");
yAxisTitle.SetText( strColumnTitle );

GeneralOffice versionmemberjbradync23 Jun '03 - 6:17 
What version of Office did you use while writing this article? More precisely, which Chart version did you use?
 
I have Office XP and it provides both the 9.0 (2000) and 10.0 (XP) versions.
 
Some (or all) of the methods you use in your code don't exist in the ClassWizard-generated interfaces for Chart 9.0.
GeneralRe: Office versionmemberAstrona20 Apr '05 - 11:41 
hmm,
i saw also MicroSoft Office Chart components v9.0 & v10.0.
 
But here the story is about
MicroSoft Chart
Questioncontrol is missing - where can i get it from ?membercsc15 Jun '03 - 20:21 
Looks pretty nice ... i've tried to use the demo on my pc, but the program does not startup.
 
I've looked for the charting control ... but i could not find it.
 
Any idea where i can get the control from ?
Please give me a "link" for a download.
 

AnswerRe: control is missing - where can i get it from ?memberjbradync16 Jun '03 - 1:24 
Most likely it is part of MS Office.
GeneralRe: control is missing - where can i get it from ?membercsc16 Jun '03 - 3:19 
Thanks, that was a good hint ...
 
- my first try was on a pc with Win 98 and MS Office 97 installed ... and there was no control Frown | :(
 
- now i've had a look on a pc with Win 2000 prof and Ms Office 2000 installed ... and there it is Big Grin | :-D
 

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 15 Jun 2003
Article Copyright 2003 by Alex C. Punnen
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid