mschart控件使用详解

合集下载

mschart控件使用详解

mschart控件使用详解

一.数据源说到绘制图表,可能很多人的第一反应除了是图表呈现的方式外,更关心的便是数据如何添加,记得在很多年前,哪时要绘制一个数据曲线图,一直找不到好的呈现方式,后来使用了SVG的绘图模式,不过在添加数据的时候可谓吃尽了苦头,毕竟,SVG只是一种描述语言,要动态的实现一个图表的绘制,是非常困难的.对于微软的图表控件,数据添加是一件很简单的方式,它支持多种数据添加方式,如:·可以在图表的设计界面,在属性设置窗口中的Series属性下的Points中添加需要的数据.·可以在图表的设计界面中,在属性中绑定一个数据源.·可以在后台代码中,动态添加数据.·可以在后台代码中设置一个或多个数据源,直接绑定到图表中.在此处,我只着重讲解一下第3,4两点.对于第3点,相对来说比较简单,在后台代码中,找到要添加代码的Series,通过它下面Points的Add、AddXY、AddY等方法,即可以实现数据的添加.例如:1. double t;2. for(t = 0; t <= (2.5 * Math.PI); t += Math.PI/6)3. {4. double ch1 = Math.Sin(t);5. double ch2 = Math.Sin(t-Math.PI/2);6. Chart1.Series["Channel 1"].Points.AddXY(t, ch1);7. Chart1.Series["Channel 2"].Points.AddXY(t, ch2);8. }复制代码注:代码摘自微软的例子,上例中,Chart1为图表的名字,Channel 1、Channel 2分别表示两个Series数据序列)二.绑定数据先来看看图表控件都支持什么类型的数据绑定,根据官方文档的说法,只要是实现了IEnumerable接口的数据类型,都可以绑定到图表控件中,例如:DataView, DataReader, DataSet, DataRow, DataColumn, Array, List, SqlCommand, OleDbCommand, SqlDataAdapter, 及OleDbDataAdapter对象。

c#_ms_chart_控件使用方法汇总(附统计图)

c#_ms_chart_控件使用方法汇总(附统计图)

c# ms chart 控件使用方法第一个简单的chart:创建曲线图chart1.Series.Clear();Series series = new Series("Spline");series.ChartType = SeriesChartType.Spline;series.BorderWidth = 3;series.ShadowOffset = 2;// Populate new series with dataseries.Points.AddY(67);series.Points.AddY(57);series.Points.AddY(83);series.Points.AddY(23);series.Points.AddY(70);series.Points.AddY(60);series.Points.AddY(90);series.Points.AddY(20);// Add series into the chart's series collectionchart1.Series.Add(series);同时显示2条曲线// Populate series with random dataRandom random = new Random();for (int pointIndex = 0; pointIndex < 10;pointIndex++){Chart1.Series["Series1"].Points.AddY(random.Next(45, 95)); Chart1.Series["Series2"].Points.AddY(random.Next(5, 75)); }// Set series chart typeChart1.Series["Series1"].ChartType = SeriesChartType.Line; Chart1.Series["Series2"].ChartType = SeriesChartType.Spline;// Set point labelsChart1.Series["Series1"].IsValueShownAsLabel = true;Chart1.Series["Series2"].IsValueShownAsLabel = true;// Enable X axis marginChart1.ChartAreas["ChartArea1"].AxisX.IsMarginVisible = true;// Enable 3D, and show data point marker linesChart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true; Chart1.Series["Series1"]["ShowMarkerLines"] = "True";Chart1.Series["Series2"]["ShowMarkerLines"] = "True";显示column类型图,柱状图// Create new data series and set it's visual attributesChart1.Series.Clear();Series series = new Series("FlowRead");series.ChartType = SeriesChartType.Column;series.BorderWidth = 3;series.ShadowOffset = 2;// Populate new series with dataseries.Points.AddY(67);series.Points.AddY(57);series.Points.AddY(83);series.Points.AddY(23);series.Points.AddY(70);series.Points.AddY(60);series.Points.AddY(90);series.Points.AddY(20);// Add series into the chart's series collectionChart1.Series.Add(series);很多点,效率还可以// Fill series datadouble yValue = 50.0;Random random = new Random();for (int pointIndex = 0; pointIndex < 20000;pointIndex++){yValue = yValue + (random.NextDouble() * 10.0 - 5.0);Chart1.Series["Series1"].Points.AddY(yValue);}// Set fast line chart typeChart1.Series["Series1"].ChartType = SeriesChartType.FastLine;日期,xy类型// Create a new random number generatorRandom rnd = new Random();// Data points X value is using current date DateTime date = DateTime.Now.Date;// Add points to the stock chart seriesfor (int index = 0; index < 10; index++){Chart1.Series["Series1"].Points.AddXY( date, // X value is a daternd.Next(40,50)); //Close Y value// Add 1 day to our X valuedate = date.AddDays(1);int-int的xy数据绘图// Create a new random number generatorRandom rnd = new Random();// Add points to the stock chart seriesfor (int index = 0; index < 10; index++){Chart1.Series["Series1"].Points.AddXY(rnd.Next(10,90), // X value is a date rnd.Next(40,50)); //Close Y value数据库数据,datetime-int类型Chart1.Series.Clear();OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");OleDbCommand cmd = conn.CreateCommand();conn.Open();mandText = "select 时间,序号from pub_log_read order by 序号asc";//DataSet ds = new DataSet();//OleDbDataAdapter da = new OleDbDataAdapter();//da.SelectCommand = cmd;//da.Fill(ds, "tbscore");OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);Chart1.DataBindTable(dr, "时间");dr.Close();数据库数据2,string-int类型Chart1.Series.Clear();OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");OleDbCommand cmd = conn.CreateCommand();conn.Open();mandText = "select 账号,count(账号) as 次数from pub_log_read group by 账号order by 账号asc";//DataSet ds = new DataSet();//OleDbDataAdapter da = new OleDbDataAdapter();//da.SelectCommand = cmd;//da.Fill(ds, "tbscore");OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);Chart1.DataBindTable(dr, "账号");dr.Close();数据库绑定3-string-int型Chart1.Series.Clear();Chart1.Series.Add("Series1");OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");OleDbCommand cmd = conn.CreateCommand();mandText = "select 账号,count(账号) as 次数from pub_log_read group by 账号order by 账号asc";conn.Open();DataSet ds = new DataSet();OleDbDataAdapter da = new OleDbDataAdapter();da.SelectCommand = cmd;da.Fill(ds, "tbscore");Chart1.DataSource = ds;Chart1.Series["Series1"].XValueMember = "账号";Chart1.Series["Series1"].YValueMembers = "次数";// Data bind to the selected data sourceChart1.DataBind();conn.Close();数据库4,只绑定yChart1.Series.Clear();Chart1.Series.Add("序号");OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");OleDbCommand cmd = conn.CreateCommand();conn.Open();mandText = "select 序号from pub_log_read order by 序号asc";//DataSet ds = new DataSet();//OleDbDataAdapter da = new OleDbDataAdapter();//da.SelectCommand = cmd;//da.Fill(ds, "tbscore");OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);Chart1.Series[0].Points.DataBindY(dr);dr.Close();数据库5,绑定xyChart1.Series.Clear();Chart1.Series.Add("序号");OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");OleDbCommand cmd = conn.CreateCommand();conn.Open();mandText = "select 账号,count(账号) as 次数from pub_log_read group by 账号order by 账号desc";//DataSet ds = new DataSet();//OleDbDataAdapter da = new OleDbDataAdapter();//da.SelectCommand = cmd;//da.Fill(ds, "tbscore");OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);Chart1.Series[0].Points.DataBindXY(dr,"账号",dr,"次数");dr.Close();数据库6,支持显示参数Chart1.Series.Clear();Chart1.Series.Add("S1");OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");OleDbCommand cmd = conn.CreateCommand();conn.Open();mandText = "SELECT * FROM REPSALES WHERE Year=2004";//DataSet ds = new DataSet();//OleDbDataAdapter da = new OleDbDataAdapter();//da.SelectCommand = cmd;//da.Fill(ds, "tbscore");OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);Chart1.Series[0].Points.DataBind(dr, "name", "sales", "Tooltip=Year,Label=Commissions{C2}");dr.Close();数据库7,支持多lineChart1.Series.Clear();Chart1.Series.Add("S1");OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");OleDbCommand cmd = conn.CreateCommand();conn.Open();mandText = "SELECT * FROM REPSALES";//DataSet ds = new DataSet();//OleDbDataAdapter da = new OleDbDataAdapter();//da.SelectCommand = cmd;//da.Fill(ds, "tbscore");OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);Chart1.DataBindCrossTable(dr, "Name", "Year", "Sales", "Label=Commissions{C}");dr.Close();数据库8,按照行添加数据// Resolve the address to the Access databasestringfileNameString = this.MapPath(".");fileNameString += "..\\..\\..\\data\\chartdata.mdb";//Initialize a connectionstringstringmyConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DataSource=" + fileNameString;// Definethe databasequerystringmySelectQuery="SELECT * FROM SALESCOUNTS;";// Createa database connection object using the connectionstringOleDbConnection myConnection = newOleDbConnection(myConnectionString);// Create adatabase command on the connection usingqueryOleDbCommandmyCommand = new OleDbCommand(mySelectQuery, myConnection);// Open theconnectionmyCommand.Connection.Open();//Initializes a new instance of the OleDbDataAdapter classOleDbDataAdapter myDataAdapter = new OleDbDataAdapter();myDataAdapter.SelectCommand = myCommand;//Initializes a new instance of the DataSet classDataSetmyDataSet = new DataSet();// Addsrows in the DataSetmyDataAdapter.Fill(myDataSet,"Query");foreach(DataRow row in myDataSet.Tables["Query"].Rows){// For each Row add a new seriesstring seriesName = row["SalesRep"].ToString();Chart1.Series.Add(seriesName);Chart1.Series[seriesName].ChartType = SeriesChartType.Line;Chart1.Series[seriesName].BorderWidth = 2;for(int colIndex = 1; colIndex <myDataSet.Tables["Query"].Columns.Count; colIndex++) {// For each column (column 1 and onward) add the value as apointstring columnName =myDataSet.Tables["Query"].Columns[colIndex].ColumnName; int YVal = (int) row[columnName];Chart1.Series[seriesName].Points.AddXY(columnName, YVal);}}DataGrid.DataSource = myDataSet;DataGrid.DataBind();// Closesthe connection to the data source. This is the preferred// method ofclosing any open connection.myCommand.Connection.Close();使用xml数据// resolve the address to the XML documentstringfileNameString = this.MapPath(".");stringfileNameSchema = this.MapPath(".");fileNameString += "..\\..\\..\\data\\data.xml";fileNameSchema += "..\\..\\..\\data\\data.xsd";//Initializes a new instance of the DataSet classDataSetcustDS = new DataSet();// Read XMLschema into the DataSet.custDS.ReadXmlSchema( fileNameSchema );// ReadXML schema and data into the DataSet.custDS.ReadXml( fileNameString );//Initializes a new instance of the DataView classDataViewfirstView = new DataView(custDS.Tables[0]);// Sincethe DataView implements and IEnumerable, pass the reader directlyinto// theDataBindTable method with the name of the column used for the Xvalue.Chart1.DataBindTable(firstView, "Name");使用excel数据// resolve the address to the Excel filestringfileNameString = this.MapPath(".");fileNameString += "..\\..\\..\\data\\ExcelData.xls";// Createconnection object by using the preceding connection string.string sConn= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +fileNameString + ";Extended Properties="Excel8.0;HDR=YES"";OleDbConnection myConnection = new OleDbConnection( sConn );myConnection.Open();// Thecode to follow uses a SQL SELECT command to display the data fromthe worksheet.// Createnew OleDbCommand to return data from worksheet.OleDbCommandmyCommand = new OleDbCommand( "Select * From[data1$A1:E25]",myConnection );// createa databasereaderOleDbDataReader myReader=myCommand.ExecuteReader(CommandBehavior.CloseConnection);//Populate the chart with data in the fileChart1.DataBindTable(myReader, "HOUR");// closethe reader and the connectionmyReader.Close();myConnection.Close();使用csv数据// Filename of the CSV filestring file= "DataFile.csv";// Getthe path of the CSV filestring path= this.MapPath(".");path +="..\\..\\..\\data\";// Createa select statement and a connection string.stringmySelectQuery = "Select * from " + file;stringConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+path+ ";Extended Properties="Text;HDR=No;FMT=Delimited"";OleDbConnection myConnection = new OleDbConnection(ConStr);// Createa database command on the connection using queryOleDbCommandmyCommand = new OleDbCommand(mySelectQuery, myConnection);// Openthe connection and create the readermyCommand.Connection.Open();OleDbDataReader myReader=myCommand.ExecuteReader(CommandBehavior.CloseConnection);// Column1 is a time value, column 2 is a double// Databindthe reader to the chart using the DataBindXY methodChart1.Series[0].Points.DataBindXY(myReader, "1", myReader,"2");// Closeconnection and data readermyReader.Close();myConnection.Close();数组绘图// Initialize an array of doublesdouble[] yval = { 2, 6, 4, 5, 3 };// Initialize an array of stringsstring[] xval = { "Peter", "Andrew", "Julie", "Mary", "Dave" };// Bind the double array to the Y axis points of the Default dataseriesChart1.Series["Series1"].Points.DataBindXY(xval, yval);数据库9,dataview// Resolve the address to the Access databasestringfileNameString = this.MapPath(".");fileNameString += "..\\..\\..\\data\\chartdata.mdb";//Initialize a connectionstringstringmyConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DataSource=" + fileNameString;// Definethe databasequerystringmySelectQuery="SELECT * FROM REPS;";// Createa database connection object using the connectionstringOleDbConnection myConnection = newOleDbConnection(myConnectionString);// Create adatabase command on the connection usingqueryOleDbCommandmyCommand = new OleDbCommand(mySelectQuery, myConnection);// Open theconnectionmyCommand.Connection.Open();//Initializes a new instance of the OleDbDataAdapter classOleDbDataAdapter custDA = new OleDbDataAdapter();custDA.SelectCommand = myCommand;//Initializes a new instance of the DataSet classDataSetcustDS = new DataSet();// Addsrows in the DataSetcustDA.Fill(custDS, "Customers");//Initializes a new instance of the DataView classDataViewfirstView = new DataView(custDS.Tables[0]);// Sincethe DataView implements IEnumerable, pass the dataview directlyinto// the DataBind method with thename of the Columns selected in thequeryChart1.Series["Default"].Points.DataBindXY(firstView,"Name",firstView, "Sales");// Closesthe connection to the data source. This is the preferred// method of closing any openconnection.myCommand.Connection.Close();指定坐标轴的数据显示范围// Create a new random number generatorRandom rnd = new Random();// Add points to the stock chart seriesfor (int index = 0; index < 10; index++){Chart1.Series["Series1"].Points.AddXY(rnd.Next(10,90), // X value is a daternd.Next(40,50)); //Close Y value}Chart1.ChartAreas[0].AxisY.Minimum = 40;Chart1.ChartAreas[0].AxisY.Maximum = 50;数据排序// Use point index for drawing the chartChart1.Series["Series1"].IsXValueIndexed = true;// Sortseries points by second Y valueChart1.DataManipulator.Sort(PointSortOrder.Ascending, "Y2","Series1");查找数据最大值和最小值// Find point with maximum Y value and change colorDataPointmaxValuePoint =Chart1.Series["Series1"].Points.FindMaxValue(); maxValuePoint.Color = Color.FromArgb(255, 128, 128);// Findpoint with minimum Y value and change colorDataPointminValuePoint =Chart1.Series["Series1"].Points.FindMinValue(); minValuePoint.Color = Color.FromArgb(128, 128, 255);pie显示交互private void Page_Load(object sender, System.EventArgs e){// Addseries to the chartSeriesseries = Chart1.Series.Add("My series");// Setseries and legend tooltipsseries.ToolTip = "#VALX: #VAL{C} million";series.LegendToolTip = "#PERCENT";series.PostBackValue = "#INDEX";series.LegendPostBackValue = "#INDEX";// Populateseries datadouble[] yValues = {65.62, 75.54, 60.45, 34.73, 85.42, 32.12, 55.18, 67.15,56.24, 23.65};string[] xValues = {"France", "Canada", "Germany", "USA", "Italy", "Russia","China", "Japan", "Sweden", "Spain" };series.Points.DataBindXY(xValues, yValues);// Setseries visual attributesseries.Type= SeriesChartType.Pie;series.ShadowOffset = 2;series.BorderColor = Color.DarkGray;series.CustomAttributes = "LabelStyle=Outside";}protected void Chart1_Click(object sender, ImageMapEventArgse){intpointIndex = int.Parse(e.PostBackValue);Seriesseries = Chart1.Series["My series"];if(pointIndex >= 0 &&pointIndex < series.Points.Count){series.Points[pointIndex].CustomProperties +="Exploded=true";}}chart点击事件/// <summary>/// Page Load event handler./// </summary>protected void Page_Load(object sender, System.EventArgs e){this.Chart1.Click += new ImageMapEventHandler(Chart1_Click);// directusing of PostBackValueforeach(Series series in this.Chart1.Series){series.PostBackValue = "series:" + + ",#INDEX";}// transferof click coordinates. getCoordinates is a javascriptfunction.stringpostbackScript =ClientScript.GetPostBackEventReference(this.Chart1,"chart:@");this.Chart1.Attributes["onclick"] = postbackScript.Replace("@'", "'+ getCoordinates(event)"); }/// <summary>/// Handles the Click event of the Chart1 control./// </summary>/// <param name="sender">The sourceof the event.</param>/// <paramname="e">The<seecref="System.Web.UI.WebControls.ImageMapEventArgs"/>instance containing the eventdata.</param>protected void Chart1_Click(object sender, ImageMapEventArgse){this.Chart1.Titles["ClickedElement"].Text = "Nothing";string[]input = e.PostBackValue.Split(':');if(input.Length == 2){string[] seriesData = input[1].Split(',');if (input[0].Equals("series")){this.Chart1.Titles["ClickedElement"].Text = "Last Clicked Element:" + seriesData[0] + " - Data Point #" + seriesData[1];}else if (input[0].Equals("chart")){// hit test of X and Y click pointHitTestResult hitTestResult=this.Chart1.HitTest(Int32.Parse(seriesData[0]),Int32.Parse(seriesData[1]));if (hitTestResult != null){this.Chart1.Titles["ClickedElement"].Text = "Last Clicked Element:" + hitTestResult.ChartElementType.ToString();}}}}。

[COM]微软MSChart图表控件使用方法

[COM]微软MSChart图表控件使用方法
}
//设计axMSChart1的数据
axMSChart1.ChartData = myay;
//设计图表的表头名称和对齐方式
axMSChart1.Title.Text = "这里是一个图表";
axMSChart1.Legend.Location.LocationType = MSChart20Lib.VtChLocationType.VtChLocationTypeRight;
{
// 设置标题
m_Chart.SetTitleText("mschart 示例 by thinkry@");
// 下面两句改变背景色
m_Chart.GetBackdrop().GetFill().SetStyle(1);
m_Chart.GetBackdrop().GetFill().GetBrush().GetFillColor().Set(255, 255, 255);
//所以我们就要空出一个位的数组来做描述
//因此数组真正的长度为ds.Tables["newtb"].Rows.Count+1
Object[,] myay=new Object[ds.Tables["newtb"].Rows.Count+1,2];
myay[0,0]=(Object)"时间描述";//这里可以不用写什么
{
int nRowCount = 6;
m_Chart.SetRowCount(nRowCount);
VARIANT var;
// 不自动标注X轴刻度
m_Chart.GetPlot().GetAxis(0,var).GetCategoryScale().SetAuto(FALSE);

使用MSChart组件绘制统计图表

使用MSChart组件绘制统计图表

22 创 建 数 据 库 表 .
在 O al 据 库 Z X 创 建 数 据 库 表 v olj _ h t 该 rce数 H X i c c _h, l
_
表数 据 来 源 于 E P系 统 或 ME R S系统 ,表 结构 如表 1 示 。 所
l c ht 表 1 原 油 进 厂情 况表 v oi jlc _h表结构
_
_
_
MA NR T N VAR HAR2 (0 N L C 4) UL
原 油来 源 编 码 物 料名 称
调 用 MSE cl0 3中 图 表 制 作 功 能 等 ,根 据 某 厂 综 合 查 询 应 x e 0 2 用 系 统 的 开 发 ,该 应 用 系 统 属 典 型 的 BS模 式 ,这 里 主 要通 过 / 当月 、当年 原 油进 厂 情 况 ( 次 的进 厂 量 、存 储 埙 耗 、途 运 埙 每
S dA dnx t i d O . e及 中文 语 言 包 MS h r c s x 。 安 装 完 后 , u o e C at I h. e e 打 开 V 2 0 ,在 创 建 项 目时 。 就 能 在 工 具 栏 中 看 到 MS h r S0 8 C at
S uc1 点 确 定 一 新 建 连 接 一 添 加 连 接 ( 改 为 Oal 据 o re ) 更 r e数 c 库 )一 输 入 服 务 器 名 zx 、用 户 名 及 密 码 测 试 连 接 成 功一 选 hx
当 月 、 当年 原 油进 厂 情 况 在 页 面左 边 以表 格 的 形式 展示 ,右 面
以 直方 图的 形 式展 示 。
2. 创 建 网 站 3
在 V 20 S0 8中创 建 A PN T网 站 ,简单 起 见 ,假 设 仅 创 建 S .E

微软图表控件MsChart使用文档

微软图表控件MsChart使用文档

一、mschart控件使用详解 3.5 ChartAreas控件中的ChartAreas属性是ChartArea对象的集合,ChartArea负责显示容器的属性或图表的背景,由于不止一个,这就意味着MSChart控件可以包含多个图表。

在使用多个ChartAreas时理解下面几点内容非常重要:在技术上可以控制ChartArea的位置,因此多个ChartArea可以叠加,但不推荐这么做,建议在MSChart 控件内的独立区域内绘制它们,为了合并或覆盖数据点,推荐在一个ChartArea内使用多个序列,后面将会有介绍。

默认情况下,控件会为你自动调整大小和位置。

单个ChartArea将会独立调整以适应数据,正如上图所显示的,第二个ChartArea中的Y值更大,数据点也更少。

多个ChartAreas控件允许你使用多个不相容的ChartTypes(序列对象属性,控制图表的显示类型,如条形、柱状和饼状)显示图表,图表任然显示在相同的MSChart控件内。

对于单个ChartArea,有许多独立的属性可以设置和调整,这样你就可以自行调整图表区域以满足不同的需要,它的大部分属性和面板控件的属性都差不多,因此这里我们就不多说了,只说一下ChartArea 唯一的属性,下面是这些唯一属性的清单:3D样式:使用ChartArea的Area3DStyle属性和子属性,我们可以创建漂亮的、十分抢眼的3D图表,无论是在设计器中还是在代码中都必需将Enable3D属性设置为TRUE,其余的参数可以通过调整旋转、视角、照明方式和其它3D元素,让一个图像看起来具有3D效果。

坐标轴控制和样式:坐标轴集合包括x轴和y轴,以及第二个x轴和y轴,这四个项目的属性允许你设置样式、设置标签、定义间隔、设置工具提示、设置缩放等,如果你的图标要求精确的间隔、标签或其它特殊的显示需要,你可以使用这些属性。

例如,你可以颠倒坐标轴的值,或控制如何在x轴上显示标签。

Microsoft Visual Studio 2010中MSChart控件用于仿真曲线样例

Microsoft Visual Studio 2010中MSChart控件用于仿真曲线样例

MSchart控件在C++6.0和Microsoft visual studio 2005中使用都需要额外安装控件,但是Microsoft visual studio 2010中已经内含此控件,所以此教程用于Microsoft visual studio 2010版本使用。

1:新建MFC工程,此处可以选择对话框程序,如图1所示,其余设置可默认。

图12:MSChart控件位于工具箱下端的常规控件选项卡中,若是工具箱面板中未找到,可以右击工具箱→选择项→COM组件中选择Microsoft Chart Control,version5.0。

控件位置及图标如图2所示。

注:此处除Microsoft Chart Control,version5.0外,还有Microsoft Chart Control 6.0,所使用的是version5.0,但添加的类却是6.0,对于此处差别还不太清楚。

图23:添加Microsoft Chart Control控件到对话框程序中,如图3所示。

图34:点击Microsoft Chart Control控件,右端出现属性窗口,如图4所示,在此处可以对于此控件进行设置,下面对于各个控件属性含义进行具体讲解。

图4更改属性页内属性,属性页位于属性列表上端快捷键最后一位,属性页如图5所示。

图5属性列表主要包括以下几个方面的设置:Chart主要包括对于图表类型的选择,此例中主要使用的是Line(2D),选项Show legend 为显示图例,在此例中需要进行勾选。

设置如图6所示。

图6Axis主要是对于各个坐标轴的设置,其中Axis可以进行X Axis、Y Axis及Second Y Axis 三个轴的选择,其中Show scale选项可以选择对应轴是否显示,Automatic scaling可以对于坐标轴上最大值、最小值、标注标签间隔和每个间隔细分格数(对于X及Y轴是不同的,X轴若是100为一个格,50需要为一个小格,Y轴Major divisions对应的是大格格数,Minor divisions对应小格格数)。

MFC画图的强大工具MSChart的使用

MFC画图的强大工具MSChart的使用

MFC画图的强⼤⼯具MSChart的使⽤MFC画图的强⼤⼯具MSChart的使⽤图表由于其直观明了的特性,在实际应⽤中⼗分很⼴泛。

我们常常希望数据能通过图表来显⽰其特性。

例如在Delphi和C++Builder编程中,我们可以很⽅便地实现数据图表。

MsChart(6.0或5.0版)是Windows 系统中Visual studio⾃带的⼀个ACTIVEX控件,它功能强⼤,应⽤⼴泛,具有以下特点:·⽀持随机数据和随机数组,动态显⽰。

·⽀持所有主要的图表类型。

·⽀持三维显⽰。

下⾯是⼀个实例:程序运⾏效果图⼀、在⼯程中加⼊mschart菜单->Project->Add To Project->Components and Controls->Registered ActiveX Controls->Microsoft Chart Control, version 6.0 (OLEDB)⼆、在CDemoView中加⼊:CMSChart m_Chart三、创建及设置m_Chart3.1 在CDemoView::OnCreate 中创建CMSChart1.// CDemoView::OnCreate()2.CRect rc;3.GetClientRect(&rc);4.if(!m_Chart.Create("mschart", WS_CHILD| WS_VISIBLE, rc, this, 10))5.return-1;3.2 在CDemoView::OnSize 中调整m_Chart 的⼤⼩,使之能随窗⼝⼤⼩变化⽽变化1.// CDemoView::OnSize2.if( m_Chart.GetSafeHwnd() )3.m_Chart.MoveWindow( 0, 0, cx, cy );3.3 设置m_Chart01.void CDemoView::InitChart()02.{03.// 设置标题04.m_Chart.SetTitleText("mschart ⽰例 by thinkry@/doc/4ce3eb7bbcd126fff7050bc0.html ");05.// 下⾯两句改变背景⾊06.m_Chart.GetBackdrop().GetFill().SetStyle(1);07.m_Chart.GetBackdrop().GetFill().GetBrush().GetFillColor().Set(255, 255, 255);08.// 显⽰图例09.m_Chart.SetShowLegend(TRUE);10.m_Chart.SetColumn(1);11.m_Chart.SetColumnLabel((LPCTSTR)"1号机");12.m_Chart.SetColumn(2);13.m_Chart.SetColumnLabel((LPCTSTR)"2号机");14.m_Chart.SetColumn(3);15.m_Chart.SetColumnLabel((LPCTSTR)"3号机");16.// 栈模式17.// m_Chart.SetStacking(TRUE);18.// Y轴设置19.VARIANT var;20.m_Chart.GetPlot().GetAxis(1,var).GetValueScale().SetAuto(FALSE); / / 不⾃动标注Y轴刻度21.m_Chart.GetPlot().GetAxis(1,var).GetValueScale().SetMaximum(100); // Y轴最⼤刻度22.m_Chart.GetPlot().GetAxis(1,var).GetValueScale().SetMinimum(0); // Y轴最⼩刻度23.m_Chart.GetPlot().GetAxis(1,var).GetValueScale().SetMajorDivision( 5); // Y轴刻度5等分24.m_Chart.GetPlot().GetAxis(1,var).GetValueScale().SetMinorDivision( 1); // 每刻度⼀个刻度线25.m_Chart.GetPlot().GetAxis(1,var).GetAxisTitle().SetText("⼩时"); // Y轴名称26.// 3条曲线27.m_Chart.SetColumnCount(3);28.// 线⾊29.m_Chart.GetPlot().GetSeriesCollection().GetItem(1).GetPen().GetVtC olor().Set(0, 0, 255);30.m_Chart.GetPlot().GetSeriesCollection().GetItem(2).GetPen().GetVtC olor().Set(255, 0, 0);31.m_Chart.GetPlot().GetSeriesCollection().GetItem(3).GetPen().GetVtC olor().Set(0, 255, 0);32.// 线宽(对点线图有效)33.m_Chart.GetPlot().GetSeriesCollection().GetItem(1).GetPen().SetWid th(50);34.m_Chart.GetPlot().GetSeriesCollection().GetItem(2).GetPen().SetWid th(100);35.m_Chart.GetPlot().GetSeriesCollection().GetItem(3).GetPen().SetWid th(2);36.// 数据点类型显⽰数据值的模式(对柱柱状图和点线图有效)37.// 0: 不显⽰ 1: 显⽰在柱状图外38.// 2: 显⽰在柱状图内上⽅ 3: 显⽰在柱状图内中间 4: 显⽰在柱状图内下⽅39.m_Chart.GetPlot().GetSeriesCollection().GetItem(1).GetDataPoints() .GetItem(-1).GetDataPointLabel().SetLocationType(1);40.m_Chart.GetPlot().GetSeriesCollection().GetItem(2).GetDataPoints() .GetItem(-1).GetDataPointLabel().SetLocationType(1);41.m_Chart.GetPlot().GetSeriesCollection().GetItem(3).GetDataPoints() .GetItem(-1).GetDataPointLabel().SetLocationType(1);42.}3.4 设置数据01.void CDemoView::DrawChart()02.{03.int nRowCount = 6;04.m_Chart.SetRowCount(nRowCount);05.VARIANT var;06.07.// 不⾃动标注X轴刻度08.m_Chart.GetPlot().GetAxis(0,var).GetCategoryScale().SetAuto(FALSE) ;09.10.// 每刻度⼀个标注11.m_Chart.GetPlot().GetAxis(0,var).GetCategoryScale().SetDivisionsPe rLabel(1);12.13.// 每刻度⼀个刻度线14.m_Chart.GetPlot().GetAxis(0,var).GetCategoryScale().SetDivisionsPe rTick(1);15.16.// X轴名称17.m_Chart.GetPlot().GetAxis(0,var).GetAxisTitle().SetText("⽇期");18.char buf[32];19.srand( (unsigned)time( NULL ) );20.for(int row = 1; row <= nRowCount; ++row)21.{22.m_Chart.SetRow(row);23.sprintf(buf, "%d号", row);24.m_Chart.SetRowLabel((LPCTSTR)buf);25.m_Chart.GetDataGrid().SetData(row, 1, rand() * 100 / RAND_MAX, 0);26.m_Chart.GetDataGrid().SetData(row, 2, rand() * 100 / RAND_MAX, 0);27.m_Chart.GetDataGrid().SetData(row, 3, rand() * 100 / RAND_MAX, 0);28.}29.m_Chart.Refresh();30.}3.5 改变显⽰类型view sourceprint?01.// 折线图02.void CDemoView::OnChartLine()03.{04.m_Chart.SetChartType(3);05.DrawChart();06.}07.08.// 柱状图09.void CDemoView::OnChartCombi()10.{11.m_Chart.SetChartType(1);12.DrawChart();13.}14.// 饼状图15.void CDemoView::OnChartPie()16.{17.m_Chart.SetChartType(14);18.DrawChart();19.}。

VC++6.0中MsChart的使用方法

VC++6.0中MsChart的使用方法

VC++6.0中MsChart的使用方法VC++6.0中MsChart的使用方法1.MSChart制图类1.1 添加MSChart控件MSChart是VC++6.0中自带的一个特殊控件类,用于绘制坐标曲线图。

如果要使用这个控件,则可以按下图的示意进行添加此控件。

1.2MSChart控件的使用方法首先在要使用的类的实现文件中包含如下头文件:#include "VcPlot.h"#include "VcAxis.h"#include "VcValueScale.h"#include "VcSeriesCollection.h"#include "VcSeries.h"#include "VcPen.h"#include "VcCategoryScale.h"#include "VcColor.h"#include "VcDataGrid.h"#include "VcBackdrop.h"#include "VcFill.h"#include "VcBrush.h"#include "VcDataPoints.h"#include "VcDataPoint.h"#include "VcDataPointLabel.h"#include "VcAxisTitle.h"#include "math.h"在要使用的类的头文件中包含:#include "mschart.h"本系统中按照如下函数调用来实现MSChart类绘制故障树重要度曲线的功能(CDrawImp是调用MSChart的类)。

VS2013 使用MsChart图表控件

VS2013 使用MsChart图表控件

VS2013 使用MsChart图表控件显示曲线波形图和数据波峰波谷标记MSChart.exe安装MSCHART注册.exeMSCHRT20.OCX也可以手动注册32位系统下:1. 将mschrt20.ocx放在windows/system32目录下。

(注意,这个文件名中的没有字母a,即没有写chart中的字母a)2.使用命令regsvr32 MSCHRT20.OCX来注册。

64位系统下:1. 确保win7管理员权限2. 把OCX控件,放到C:\Windows\SysWow64路径下面3. 进入cmd,管理员权限运行4. regsvr32 C:\Windows\SysWow64\MSCHRT20.OCX注册成功会提示的。

在VS2013的对话框中的应用如下:打开VS2013,新建一个MFC工程,点击VS中的“工具->选择工具箱->COM组件”,找到Microsoft Chart Control,version 6.0(OLEDB)并勾选上。

接下来,就可以在工具箱中看到该控件首先建立一个基于对话框的工程文件,在对话框界面单击右键->插入Activex控件->Microsoft Chart Control,version 6.0(OLEDB)即可。

新建MFC工程建立对话框应该程序点击完成,右击插入ActiveX控件列表中找到Microsoft Chart Control 6.0(SP4) (OLEDB)控件点确定按钮插入MsChart图表控件在控件上右击添加变量这时候并不能使用MsChart控件的所有功能,还需要添加控件的所有类,添加步骤如下,先打开类向导点“…”找到MSCHRT20.OCX文件注意OCX控件32位系统在C:\ windows/system32目录下64位系统在C:\Windows\SysWow64路径下面注意左侧会列出控件的所有类,可选择添加点击“>”逐个添加要用到的类,好像只能一个一个添加,最好全部添加添加完成按确定会自动加载.h和.cpp文件到工程中,这时才可以使用控件的所有功能下面是整理出来的一些主要功能void CMyPD3000Dlg::Init_Mschart(CMschart1& m_chartt1){m_chartt1.put_AllowSelections(FALSE); //是否可以选择图表对象m_chartt1.put_AllowSeriesSelection(FALSE);//单击单个的图表数据点时是否可选定整个系列。

MSChart图表控件的一些使用

MSChart图表控件的一些使用

MSChart图表控件的一些使用最近使用MSChart做了几张图表,微软提供的例子中对这个图表控件的使用已经说的比较详细了,我这里记录一些需要注意的。

1. Chart图表的元素要使用该图表首先要了解该图表的元素组成,就是下面这张图了,图表主要包含:Annotations (图形注解集合)ChartAreas(图表区域集合)Legends(图例集合)Series图表序列集合即图表数据对象集合)Title(图标的标题集合)其他大家可以参考Samples中的Char Features一节。

2. 如何在 MVC中使用Chart控件2.1.需要在"<system.web><pages><controls>"中添加如下:<add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization,Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>2.2.在"<httpHandlers>"中添加如下部分:<add path="ChartImg.axd" verb="GET,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHan dler,System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>2.3. 有了上面的配置就可以测试了:2.3.1.View中添加:<asp:chart id="Chart1" runat="server" Height="296px"Width="412px" Palette="BrightPastel" imagetype="Png"BorderDashStyle="Solid" BackSecondaryColor="White" BackGradientStyle="TopBottom" BorderWidth="2" backcolor="#D3DFF0"BorderColor="26, 59, 105"><Titles><asp:Title Text="With datasource in code behind" /></Titles><legends><asp:Legend IsTextAutoFit="False" Name="Default" BackColor="Transparent" Font="Trebuchet MS, 8.25pt, style=Bold"></asp:Legend></legends><borderskin skinstyle="Emboss"></borderskin><series><asp:Series Name="Column" BorderColor="180, 26, 59, 105"> </asp:Series></series><chartareas><asp:ChartArea Name="ChartArea1" BorderColor="64, 64, 64, 64" BorderDashStyle="Solid" BackSecondaryColor="White"BackColor="64, 165, 191, 228" ShadowColor="Transparent" BackGradientStyle="TopBottom"><area3dstyle Rotation="10" perspective="10" Inclination="15" IsRightAngleAxes="False" wallwidth="0"IsClustered="False"></area3dstyle><axisy linecolor="64, 64, 64, 64"><labelstyle font="Trebuchet MS, 8.25pt, style=Bold" /><majorgrid linecolor="64, 64, 64, 64" /></axisy><axisx linecolor="64, 64, 64, 64"><labelstyle font="Trebuchet MS, 8.25pt, style=Bold" /><majorgrid linecolor="64, 64, 64, 64" /></axisx></asp:ChartArea></chartareas></asp:chart>2.3.2.index.aspx.cs中添加protected void Page_Load(object sender, System.EventArgs e) {foreach (int value in (List<int>)this.ViewData["Chart"]){this.Chart1.Series["Column"].Points.Add(value);}}2.3.3.Controller中:public ActionResult Index(){ViewData["Title"] = "Home Page";ViewData["Message"] = "Welcome to MVC!";List<int> chartList = new List<int>();chartList.Add(1);chartList.Add(2);chartList.Add(6);chartList.Add(5);chartList.Add(4);ViewData["Chart"] = chartList;return View();}2.3.4.添加System.Web.ui.DataVisualization引用3. Tooltip的使用ToolTip用于在各个关键点,如:标签、图形关键点、标题等当鼠标移动上去的时候,提示用户一些相关的详细或说明信息。

Chart控件---饼图基本用法

Chart控件---饼图基本用法

Chart控件---饼图基本⽤法我对Chart控件的认识MSChart控件,给图形统计和报表图像显⽰提供了很好的解决办法,有先数据直接就能在图表上显⽰出来,给使⽤者带来了极⼤⽅便。

基本⽤法在VS⾥⾯直接把Chart 空间拖⼊到页⾯中,在后台绑定好xValues,yValues的值,然后在加⼊圆饼的百分⽐此时就把简单的饼图给显⽰出来了。

如何绑定xValues,yValues的值重要的是我们如何绑定xValues,yValues的值 ,xValues的值就是从数据源中得到的如上图化学⼯业、⾮煤矿⼭等都是绑定到xValues上的值,yValues的值就是化学⼯业等所占企业总和的百分⽐;然后写⼊以下代码就把xValues,yValues值绑定了。

Chart2.Series["Series1"].Points.DataBindXY(xValues, yValues); 其中Chart2是饼图的名字,Series是图表序列,通俗点说就是实际的绘图数据区域,实际呈现图形形状就是由此集合中的每⼀个图表构成可以往集合中添加多个图表,每⼀个图表都有⾃⼰的呈现的图像、样式和独⽴的数据;DataBindXY()⾥⾯实际上传的是⼀个数的集合。

如何得到xValues,yValues 的值DataBindXY()⾥⾯放的就是xValues,yValues 的集合,我们可以从数据库中把⾃⼰想要加到xValues上的值⼀⼀存放到⼀个集合中然后在绑定到xValues,我们也可以把读取的数据直接放到xValues⾥⾯。

如过是通过SqlDataReader直接读出来放进去可以这样做SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);Chart1.Series["Series1"].Points.DataBindXY(dr, "orgname", dr, "dd"); 其中orgname 是xValues的值,dd是yValues上的值。

MSChart控件教程

MSChart控件教程

MSChart控件教程MSChart控件这些内容是在学习过程中进行的整理,由于感到书籍资料或软件帮助中有时让人很不容易理解,特制作这个教程,以方便其他朋友学习,从新学习此控件的人的角度来描述相应的属性,相信也能让跟我一样程度的人更容易理解,可能在学习的过程中对某些属性与方法有理解不正确,请各位指正。

附录:1、AllowDynamicRotation作用:返回或设置是否可旋转图表注:需要图表的ChartType是3d类型才可以,当AllowDynamicRotation=True时,在图表中可按住ctrl+鼠标左键旋转图表。

示例:下列代码在窗体加载时将MSChart1设置为3d柱形图,并允许按住ctrl+鼠标左键旋转。

(窗体上放一个MSChart控件)Private Sub Form_Load()With MSChart1.chartType = VtChChartType3dBar '类型为3d柱形图,类形常数详见附录.AllowDynamicRotation = True '允许旋转End WithEnd Sub下列代码将以对话框的形式返回上面示例的AllowDynamicRotation值:MsgBox MSChart1.AllowDynamicRotation2、ChartData注:书中及软件帮助文档中说到数组需要变体型数值,是指如果要将数组第一个元素作为标题,其他作为数据,那个这个数组既有字符又有数字,那么就需要一个变体形。

如果数组中并不包含标题(或是之后使用属性来赋于标题),那么数组是可以定义类形的,个人建议先给定数组类型,之后再使用属性来设置标题。

作用:设置:将一个数组的数据作表图表的显示数据返回:将图表数据赋给一个数组示例:将数组元素作为图表的显示数据制作一个1行6列的的图表(数组的维代表图表的行,每维的元素代表列)Private Sub Form_Load()Dim 一维数组(1 To 6)'为了表示得更清楚,我们采取逐个赋值的方法一维数组(1) = 1一维数组(2) = 2一维数组(3) = 3一维数组(4) = 4一维数组(5) = 5一维数组(6) = 6With MSChart1.chartType = VtChChartType2dBar '类型为3d柱形图.ChartData = 一维数组()End WithEnd Sub为了理解图表的行列与数组的维数的对应关系,再举例一个二维数组(图表对应就形成2行6列)Private Sub Form_Load() Dim 二维数组(1 To 2, 1 To 6)'为了表示得更清楚,我们采取逐个赋值的方法二维数组(1, 1) = 1二维数组(1, 2) = 2二维数组(1, 3) = 3二维数组(1, 4) = 4二维数组(1, 5) = 5二维数组(1, 6) = 6二维数组(2, 1) = 1二维数组(2, 2) = 2二维数组(2, 3) = 3二维数组(2, 4) = 4二维数组(2, 5) = 5二维数组(2, 6) = 6With MSChart1.chartType = VtChChartType2dBar '类型为2d柱形图.ChartData = 二维数组()End WithEnd Sub下面是将数组的第一个元素设置成字符,使图表加载时将其作为标题的示例:Private Sub Form_Load()Dim 二维数组(1 To 2, 1 To 6)'为了表示得更清楚,我们采取逐个赋值的方法二维数组(1, 1) = "第一行标题"二维数组(1, 2) = 2二维数组(1, 3) = 3二维数组(1, 4) = 4二维数组(1, 5) = 5二维数组(1, 6) = 6二维数组(2, 1) = "第二行标题"二维数组(2, 2) = 5二维数组(2, 3) = 4二维数组(2, 4) = 3二维数组(2, 5) = 2二维数组(2, 6) = 1With MSChart1.chartType = VtChChartType2dBar '类型为2d柱形图.ChartData = 二维数组()End WithEnd Sub最后总结数组元素与维和图表行列的对应关系,作以下关系图:上述例子是将数组的内容反应到图表中,下面我们将使用上面的一维和二维图表,从图表中获得数据给数组,并将数组显示出来以验证结果(我们采取设置一个断点,然后通过视图\本地的方式来查看生成的数组):从图中可以看到,对于我们用2给数组生成的图表,再赋给新的数组时,数组变成了3维,并且每维还多了一个元素用来存储行标签,既“R1”、“R2”,多出来的一维用来存储列标签,既“C1”、“C2”等。

MSCHART用法

MSCHART用法

1、MSChart控件的属性(1)ChartType属性:用于设置或返回图表类型,MSChart控件图表类型与对应ChartType属性值如表8.7所示。

如,ChartType=1则显示二维直方图,ChartType=14则显示饼图。

表8.7 MSChart图表类型(2)行(格)属性①RowCount属性:用于表示图表中总格(行)数。

例如:若MSChart控件显示二维数组Array_2(M,N),则总格(行)数RowCount=M。

如:RowCount=5,表示有5格(行)数据。

若MSChart控件显示一维数组Array_1(N)的元素值,则总行数RowCount=1。

②Row属性:用于表示图表中某格(行)的序号。

若MSChart控件显示二维数组Array_2(M,N),则图表中第I格的序号Row=I,当Row=1表示第1格(行)数据。

③RowLabel属性:用于表示格(行)标签名,默认值为Ri。

用户可以修改其值,如改为无锡地区人数、南京地区人数等。

④RowLabelCount属性:用于表示格(行)标签数,MSChart控件允许设置多个格(行)标签。

通常取值为1,当需要用2行以上的标签时,才修改此属性。

⑤RowLabelIndex属性:用于表示格(行)标签序号,用户通过设置不同格(行)标签序号选择不同格(行)标签进行编辑。

(3)列属性①ColumnCount属性:用于表示图表中每格(行)中的列数,即数组中列数N。

如设置ColumnCount=3,则每格(行)中有3列,图表每数据格用3个矩形或3个扇形表示。

②Column属性:用于表示图表中某格(行)某列的列序号,例如:Row=1,Column=1,表示图表中第1格(行)第1列。

③ColumnLabel属性:用于表示图表列标签名,默认为Ci。

④ColumnLabelCount属性:用于表示图表某格中的列标签数。

⑤ColumnLabelIndex属性:用于表示图表某格中的列标签序号。

VS_MSChart控件的安装及应用

VS_MSChart控件的安装及应用

VS_MSChart控件的安装及应用1. 安装在VS中使用 Chart 控件的要求是 .net framework service pack 1准备 4 个文件,分别是:dotnetfx35sp1.exe(若当前 framework 版本为 sp1.1 就不需要装这个了)MSChart.exeMSChart_VisualStudioAddOn.exeMSChartLP_chs.exe顺序:MSChart.exeMSChart_VisualStudioAddOn.exe(至此,打开 VS 可看到工具箱中新增了[data]选项卡,下面有 Chart 控件)注意:安装时 VS 需要关闭安装中遇到的问题的小结:运行 dotNetFx35setup.exe 时,首先会提示下载,下载完毕之后进入安装。

但安装出错,报错原因为 dotnetfx2.0 SP1、dotnetfx3.0 SP1 安装不正确,错误代码 1603。

根据网上的资料,需要先清除系统中所有的 .net framework,然后重新安装。

清除时使用 microsoft 的工具dotnetfx_cleanup_tool 完全清除。

之后关闭 Cryptographic Services 服务,并删除system32\catroot2 目录下的所有内容。

再重新启动 Cryptographic Services 服务。

打开 dotnetfx35\wcu\dotNetFramework\dotNetFX30 目录,找到 WIC_x86_enu.exe,点击安装。

之后安装 dotnetfx35\wcu\dotNetFramework 目录中的 dotNetFx35setup.exe 独立安装包即可成功。

2. 使用需要添加如下引用System.Windows.Forms.DataVisualization.dll并导入如下命名空间using System.Windows.Forms.DataVisualization.Charting;但是这个命名空间只有在安装了 ChartControl.exe 之后才能在添加引用窗口中的 .NET 组件中找到,但是要安装 ChartControl 组件,需要当前的系统环境为 .net framework 3.5 SP1。

MSChart控件的用法

MSChart控件的用法

介绍MSChart的常用属性和事件介绍MSChart的常用属性和事件MSChart的元素组成最常用的属性包括ChartAreas:增加多个绘图区域,每个绘图区域包含独立的图表组、数据源,用于多个图表类型在一个绘图区不兼容时。

AlignmentOrientation:图表区对齐方向,定义两个绘图区域间的对齐方式。

AlignmentStyle:图表区对齐类型,定义图表间用以对其的元素。

AlignWithChartArea:参照对齐的绘图区名称。

InnerPlotPosition:图表在绘图区内的位置属性。

Auto:是否自动对齐。

Height:图表在绘图区内的高度(百分比,取值在0-100)Width:图表在绘图区内的宽度(百分比,取值在0-100)X,Y:图表在绘图区内左上角坐标Position:绘图区位置属性,同InnerPlotPosition。

Name:绘图区名称。

Axis:坐标轴集合Title:坐标轴标题TitleAlignment:坐标轴标题对齐方式Interval:轴刻度间隔大小IntervalOffset:轴刻度偏移量大小MinorGrid:次要辅助线MinorTickMark:次要刻度线MajorGrid:主要辅助线MajorTickMark:主要刻度线DataSourceID:MSChart的数据源。

Legends:图例说明。

Palette:图表外观定义。

Series:最重要的属性,图表集合,就是最终看到的饼图、柱状图、线图、点图等构成的集合;可以将多种相互兼容的类型放在一个绘图区域内,形成复合图。

IsValueShownAsLabel:是否显示数据点标签,如果为true,在图表中显示每一个数据值Label:数据点标签文本LabelFormat:数据点标签文本格式LabelAngle:标签字体角度Name:图表名称Points:数据点集合XValueType:横坐标轴类型YValueType:纵坐标轴类型XValueMember:横坐标绑定的数据源(如果数据源为T able,则填写横坐标要显示的字段名称)YValueMembers:纵坐标绑定的数据源(如果数据源为Table,则填写纵坐标要显示的字段名称,纵坐标可以有两个)ChartArea:图表所属的绘图区域名称ChartType:图表类型(柱形、饼形、线形、点形等)Legend:图表使用的图例名称Titles:标题集合。

图表绘制控件mschart的使用方法1

图表绘制控件mschart的使用方法1

图表绘制控件mschart的使⽤⽅法1VisualBasic中ActiveX控件MSChart的使⽤⽅法*依⽪提哈尔·穆罕买提,那斯尔江·⼟尔逊(新疆⼤学数学与系统科学学院,乌鲁⽊齐,830046)热依曼·吐尔逊(新疆⼤学信息⼯程学院,乌鲁⽊齐,830046)摘要:本⽂⾸先介绍了VisualBasic(简称VB)中MSChart控件的使⽤⽅法,然后通过简单的例⼦详细介绍了利⽤MSChart控件绘制Excel数据源图表的⽅法。

关键词:VisualBasic;MSChart控件;MicrosoftExcel数据表;图表;数据库The Methods of Using MSChart Control Based on VBIptihar.Muhammat,Nasirjan.Tursun(Mathematics and Systematic Science Institude of XinjiangUniversity,Urumqi,Xinjiang,830046)Reyima.Tursun(Information Science and Engineering Institude of Xinjiang University,Urumqi,Xinjiang,830046)Abstract:This article discusses how to use the MSChart control and how that is used in the VB project to drawing Microsoft? Excel charts.KeyWords: MSChart Control;Chartdata ;Mirosoft Excel Sheets;Chart;Database1. 引⾔Visual Basic中的MSChart控件是⼀个功能强⼤的⾼级图表⼯具,拥有丰富的图表绘制功能,⽤它来可以显⽰⼆维和三维的棒图、区域图、线形图、饼图等多种常⽤图表。

MSChart的使用

MSChart的使用

MSChart的使用编写人:少将日期:2011-02-231.下载并注册MSCHRT20.OCX控件 (1)2.添加MSChart控件 (1)3.需要使用的头文件 (2)4.类中定义变量和方法 (3)5.在对话框的OnInitDialog()函数中 (4)6.在对话框的OnSize()函数中 (5)7.完成initmschart() (5)8.完成DrawChart() (7)9.完成OnChartLine()、OnChartCombi()、OnChartPie() (8)1.下载并注册MSCHRT20.OCX控件下载MSChart6.0,并通过regsvr32进行注册2.添加MSChart控件3.需要使用的头文件首先在要使用的类的实现文件中包含如下头文件:#include "VcPlot.h"#include "VcAxis.h"#include "VcValueScale.h"#include "VcSeriesCollection.h"#include "VcSeries.h"#include "VcPen.h"#include "VcCategoryScale.h"#include "VcColor.h"#include "VcDataGrid.h"#include "VcBackdrop.h"#include "VcFill.h"#include "VcBrush.h"#include "VcDataPoints.h"#include "VcDataPoint.h"#include "VcDataPointLabel.h"#include "VcAxisTitle.h"#include "math.h"#include "VcAxisGrid.h"#include "VcAxisScale.h"在要使用的类的头文件中包含:#include "mschart.h"4.类中定义变量和方法class CTestMSChartDlg : public CDialog{// Constructionpublic:CTestMSChartDlg(CWnd* pParent = NULL); // standard constructor// Dialog Data//{{AFX_DATA(CTestMSChartDlg)enum { IDD = IDD_TESTMSCHART_DIALOG };// NOTE: the ClassWizard will add data members here//}}AFX_DATA// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CTestMSChartDlg)protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL// Implementationprotected:HICON m_hIcon;// Generated message map functions//{{AFX_MSG(CTestMSChartDlg)virtual BOOL OnInitDialog();afx_msg void OnSysCommand(UINT nID, LPARAM lParam);afx_msg void OnPaint();afx_msg HCURSOR OnQueryDragIcon();afx_msg void OnSize(UINT nType, int cx, int cy);afx_msg void OnBtnline();afx_msg void OnBtncombi();afx_msg void OnBtnpie();//}}AFX_MSGDECLARE_MESSAGE_MAP()private:void DrawChart();void initmschart();void OnChartLine();void OnChartCombi();void OnChartPie();CMSChart m_Chart;};5.在对话框的OnInitDialog()函数中BOOL CTestMSChartDlg::OnInitDialog(){CDialog::OnInitDialog();// Add "About..." menu item to system menu.// IDM_ABOUTBOX must be in the system command range.ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);ASSERT(IDM_ABOUTBOX < 0xF000);CMenu* pSysMenu = GetSystemMenu(FALSE);if (pSysMenu != NULL){CString strAboutMenu;strAboutMenu.LoadString(IDS_ABOUTBOX);if (!strAboutMenu.IsEmpty()){pSysMenu->AppendMenu(MF_SEPARATOR);pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);}}// Set the icon for this dialog. The framework does this automatically// when the application's main window is not a dialogSetIcon(m_hIcon, TRUE); // Set big iconSetIcon(m_hIcon, FALSE); // Set small icon// TODO: Add extra initialization here//创建图表CRect rc;GetClientRect(&rc);rc.bottom-=50;m_Chart.Create("mschart", WS_CHILD| WS_VISIBLE, rc, this, 10);initmschart();DrawChart();//折线图OnChartLine();//条状图//OnChartCombi();//饼状图//OnChartPie();return TRUE; // return TRUE unless you set the focus to a control}6.在对话框的OnSize()函数中//控件自适应窗口大小void CTestMSChartDlg::OnSize(UINT nType, int cx, int cy){CDialog::OnSize(nType, cx, cy);// TODO: Add your message handler code hereif( m_Chart.GetSafeHwnd() )m_Chart.MoveWindow( 0, 0, cx, cy );}7.完成initmschart()//初始化图表void CTestMSChartDlg::initmschart(){// 设置标题m_Chart.SetTitleText("mschart 示例");// 下面两句改变背景色m_Chart.GetBackdrop().GetFill().SetStyle(1);m_Chart.GetBackdrop().GetFill().GetBrush().GetFillColor().Set(255, 255, 255);// 显示图例m_Chart.SetShowLegend(TRUE);m_Chart.SetColumn(1);m_Chart.SetColumnLabel((LPCTSTR)"1号机");m_Chart.SetColumn(2);m_Chart.SetColumnLabel((LPCTSTR)"2号机");m_Chart.SetColumn(3);m_Chart.SetColumnLabel((LPCTSTR)"3号机");// 栈模式//m_Chart.SetStacking(TRUE);//X轴设置m_Chart.SetRowCount(6);char buf[32];for(int row=1;row<=6;++row){m_Chart.SetRow(row);sprintf(buf, "%d号", row);m_Chart.SetRowLabel((LPCTSTR)buf);}V ARIANT varX;// 不自动标注X轴刻度m_Chart.GetPlot().GetAxis(0,varX).GetCategoryScale().SetAuto(FALSE);// 每刻度一个标注m_Chart.GetPlot().GetAxis(0,varX).GetCategoryScale().SetDivisionsPerLabel(1);// 每刻度一个刻度线m_Chart.GetPlot().GetAxis(0,varX).GetCategoryScale().SetDivisionsPerTick(1);// X轴名称m_Chart.GetPlot().GetAxis(0,varX).GetAxisTitle().SetText("日期");// Y轴设置V ARIANT varY;m_Chart.GetPlot().GetAxis(1,varY).GetValueScale().SetAuto(FALSE); // 不自动标注Y 轴刻度m_Chart.GetPlot().GetAxis(1,varY).GetValueScale().SetMaximum(100); // Y轴最大刻度m_Chart.GetPlot().GetAxis(1,varY).GetValueScale().SetMinimum(0); // Y轴最小刻度m_Chart.GetPlot().GetAxis(1,varY).GetValueScale().SetMajorDivision(5); // Y轴刻度5等分m_Chart.GetPlot().GetAxis(1,varY).GetValueScale().SetMinorDivision(1); // 每刻度一个刻度线m_Chart.GetPlot().GetAxis(1,varY).GetAxisTitle().SetText("小时"); // Y轴名称// 3条曲线m_Chart.SetColumnCount(3);// 线色m_Chart.GetPlot().GetSeriesCollection().GetItem(1).GetPen().GetVtColor().Set(0, 0, 255);m_Chart.GetPlot().GetSeriesCollection().GetItem(2).GetPen().GetVtColor().Set(255, 0, 0);m_Chart.GetPlot().GetSeriesCollection().GetItem(3).GetPen().GetVtColor().Set(0, 255, 0);// 线宽(对点线图有效)m_Chart.GetPlot().GetSeriesCollection().GetItem(1).GetPen().SetWidth(50);m_Chart.GetPlot().GetSeriesCollection().GetItem(2).GetPen().SetWidth(100);m_Chart.GetPlot().GetSeriesCollection().GetItem(3).GetPen().SetWidth(2);// 数据点类型显示数据值的模式(对柱柱状图和点线图有效)// 0: 不显示1: 显示在柱状图外// 2: 显示在柱状图内上方3: 显示在柱状图内中间4: 显示在柱状图内下方m_Chart.GetPlot().GetSeriesCollection().GetItem(1).GetDataPoints().GetItem(-1).GetD ataPointLabel().SetLocationType(1);m_Chart.GetPlot().GetSeriesCollection().GetItem(2).GetDataPoints().GetItem(-1).GetD ataPointLabel().SetLocationType(1);m_Chart.GetPlot().GetSeriesCollection().GetItem(3).GetDataPoints().GetItem(-1).GetD ataPointLabel().SetLocationType(1);//不要与x轴垂直的表格线m_Chart.GetPlot().GetAxis(0,varX).GetAxisGrid().GetMajorPen().SetStyle(0);// no x grids//隐藏第二y轴,即右边的y轴m_Chart.GetPlot().GetAxis(2,varY).GetAxisScale().SetHide(TRUE);}8.完成DrawChart()//设置数据void CTestMSChartDlg::DrawChart(){/*int nRowCount = 6;char buf[32];srand( (unsigned)time( NULL ) );for(int row = 1; row <= nRowCount; ++row){m_Chart.SetRow(row);sprintf(buf, "%d号", row);m_Chart.SetRowLabel((LPCTSTR)buf);m_Chart.GetDataGrid().SetData(row, 1, rand() * 100 / RAND_MAX, 0);m_Chart.GetDataGrid().SetData(row, 2, rand() * 100 / RAND_MAX, 0);m_Chart.GetDataGrid().SetData(row, 3, rand() * 100 / RAND_MAX, 0);}*/for(int row=1;row<=6;++row){m_Chart.GetDataGrid().SetData(row, 1, 11*row, 0);m_Chart.GetDataGrid().SetData(row, 2, 22*row, 0);m_Chart.GetDataGrid().SetData(row, 3, 33*row, 0);}m_Chart.Refresh();m_Chart.EditCopy();}9.完成OnChartLine()、OnChartCombi()、OnChartPie()/*设置图例类型3:曲线型;1:条形;14:饼图,0:三维显示,1:二维显示m_Chart.SetChartType(1|0) //2D柱(条)形,m_Chart.SetChartType(0|0) //3D柱(条)形m_Chart.SetChartType(1|2) //2D线条型m_Chart.SetChartType(0|2) //3D线条型m_Chart.SetChartType(1|4) //2D区域型m_Chart.SetChartType(0|4) //3D区域型m_Chart.SetChartType(1|6) //2D阶梯型m_Chart.SetChartType(0|6) //3D阶梯型m_Chart.SetChartType(1|8) //2D复(混)合型m_Chart.SetChartType(0|8) //3D复(混)合型另外,在2D方式中,还有两类:饼型和XY型m_Chart.SetChartType(14) //2D 饼型m_Chart.SetChartType(16) //2DXY型*/// 折线图void CTestMSChartDlg::OnChartLine(){m_Chart.SetChartType(3); DrawChart();}// 柱状图void CTestMSChartDlg::OnChartCombi() {m_Chart.SetChartType(1); DrawChart();}// 饼状图void CTestMSChartDlg::OnChartPie() {m_Chart.SetChartType(14); DrawChart();}。

MSChart控件

MSChart控件

一、在工程中加入 mschart菜单->Project->Add To Project->Components and Controls->Registered ActiveX Controls->Microsoft Chart Control, version 6.0 (OLEDB)二、在CDemoView中加入:CMSChart m_Chart三、创建及设置m_Chart3.1 在 CDemoView::OnCreate 中创建CMSChart// CDemoView::OnCreate()CRect rc;GetClientRect(&rc);if(!m_Chart.Create("mschart", WS_CHILD| WS_VISIBLE, rc, this, 10)) return -1;3.2 在 CDemoView::OnSize 中调整 m_Chart 的大小,使之能随窗口大小变化而变化 // CDemoView::OnSizeif( m_Chart.GetSafeHwnd() )m_Chart.MoveWindow( 0, 0, cx, cy );3.3 设置 m_Chart void CDemoView::InitChart(){// 设置标题m_Chart.SetTitleText("mschart 示例");// 下面两句改变背景色m_Chart.GetBackdrop().GetFill().SetStyle(1);m_Chart.GetBackdrop().GetFill().GetBrush().GetFillColor().Set(255, 255, 255);// 显示图例m_Chart.SetShowLegend(TRUE);m_Chart.SetColumn(1);m_Chart.SetColumnLabel((LPCTSTR)"1号机");m_Chart.SetColumn(2);m_Chart.SetColumnLabel((LPCTSTR)"2号机");m_Chart.SetColumn(3);m_Chart.SetColumnLabel((LPCTSTR)"3号机");// 栈模式// m_Chart.SetStacking(TRUE);// Y轴设置VARIANT var;m_Chart.GetPlot().GetAxis(1,var).GetValueScale().SetAuto(FALSE); // 不自动标注Y轴刻度m_Chart.GetPlot().GetAxis(1,var).GetValueScale().SetMaximum(100); // Y轴最大刻度m_Chart.GetPlot().GetAxis(1,var).GetValueScale().SetMinimum(0); // Y 轴最小刻度m_Chart.GetPlot().GetAxis(1,var).GetValueScale().SetMajorDivision(5); // Y轴刻度5等分m_Chart.GetPlot().GetAxis(1,var).GetValueScale().SetMinorDivision(1); // 每刻度一个刻度线m_Chart.GetPlot().GetAxis(1,var).GetAxisTitle().SetText("小时"); // Y 轴名称// 3条曲线m_Chart.SetColumnCount(3);// 线色m_Chart.GetPlot().GetSeriesCollection().GetItem(1).GetPen().GetVtCol or().Set(0, 0, 255);m_Chart.GetPlot().GetSeriesCollection().GetItem(2).GetPen().GetVtCol or().Set(255, 0, 0);m_Chart.GetPlot().GetSeriesCollection().GetItem(3).GetPen().GetVtCol or().Set(0, 255, 0);// 线宽(对点线图有效)m_Chart.GetPlot().GetSeriesCollection().GetItem(1).GetPen().SetWidth (50);m_Chart.GetPlot().GetSeriesCollection().GetItem(2).GetPen().SetWidth (100);m_Chart.GetPlot().GetSeriesCollection().GetItem(3).GetPen().SetWidth (2);// 数据点类型显示数据值的模式(对柱柱状图和点线图有效)// 0: 不显示 1: 显示在柱状图外// 2: 显示在柱状图内上方 3: 显示在柱状图内中间 4: 显示在柱状图内下方 m_Chart.GetPlot().GetSeriesCollection().GetItem(1).GetDataPoints().G etItem(-1).GetDataPointLabel().SetLocationType(1);m_Chart.GetPlot().GetSeriesCollection().GetItem(2).GetDataPoints().G etItem(-1).GetDataPointLabel().SetLocationType(1);m_Chart.GetPlot().GetSeriesCollection().GetItem(3).GetDataPoints().G etItem(-1).GetDataPointLabel().SetLocationType(1);}3.4 设置数据 void CDemoView::DrawChart(){int nRowCount = 6;m_Chart.SetRowCount(nRowCount);VARIANT var;// 不自动标注X轴刻度m_Chart.GetPlot().GetAxis(0,var).GetCategoryScale().SetAuto(FALSE);// 每刻度一个标注m_Chart.GetPlot().GetAxis(0,var).GetCategoryScale().SetDivisionsPerL abel(1);// 每刻度一个刻度线m_Chart.GetPlot().GetAxis(0,var).GetCategoryScale().SetDivisionsPerT ick(1);// X轴名称m_Chart.GetPlot().GetAxis(0,var).GetAxisTitle().SetText("日期"); char buf[32];srand( (unsigned)time( NULL ) );for(int row = 1; row <= nRowCount; ++row){m_Chart.SetRow(row);sprintf(buf, "%d号", row);m_Chart.SetRowLabel((LPCTSTR)buf);m_Chart.GetDataGrid().SetData(row, 1, rand() * 100 / RAND_MAX, 0); m_Chart.GetDataGrid().SetData(row, 2, rand() * 100 / RAND_MAX, 0); m_Chart.GetDataGrid().SetData(row, 3, rand() * 100 / RAND_MAX, 0); }m_Chart.Refresh();}3.5 改变显示类型 // 折线图void CDemoView::OnChartLine(){m_Chart.SetChartType(3);DrawChart();}// 柱状图void CDemoView::OnChartCombi(){m_Chart.SetChartType(1);DrawChart();}// 饼状图void CDemoView::OnChartPie(){m_Chart.SetChartType(14);DrawChart();}//////////////////////////////////在设计使用上没问题,vs2005的,但做成安装包在其它电脑上安装运行出错(14007)。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

一.数据源说到绘制图表,可能很多人的第一反应除了是图表呈现的方式外,更关心的便是数据如何添加,记得在很多年前,哪时要绘制一个数据曲线图,一直找不到好的呈现方式,后来使用了SVG的绘图模式,不过在添加数据的时候可谓吃尽了苦头,毕竟,SVG只是一种描述语言,要动态的实现一个图表的绘制,是非常困难的.对于微软的图表控件,数据添加是一件很简单的方式,它支持多种数据添加方式,如:·可以在图表的设计界面,在属性设置窗口中的Series属性下的Points中添加需要的数据.·可以在图表的设计界面中,在属性中绑定一个数据源.·可以在后台代码中,动态添加数据.·可以在后台代码中设置一个或多个数据源,直接绑定到图表中.在此处,我只着重讲解一下第3,4两点.对于第3点,相对来说比较简单,在后台代码中,找到要添加代码的Series,通过它下面Points的Add、AddXY、AddY等方法,即可以实现数据的添加.例如:1. double t;2. for(t = 0; t <= (2.5 * Math.PI); t += Math.PI/6)3. {4. double ch1 = Math.Sin(t);5. double ch2 = Math.Sin(t-Math.PI/2);6. Chart1.Series["Channel 1"].Points.AddXY(t, ch1);7. Chart1.Series["Channel 2"].Points.AddXY(t, ch2);8. }复制代码注:代码摘自微软的例子,上例中,Chart1为图表的名字,Channel 1、Channel 2分别表示两个Series数据序列)二.绑定数据先来看看图表控件都支持什么类型的数据绑定,根据官方文档的说法,只要是实现了IEnumerable接口的数据类型,都可以绑定到图表控件中,例如:DataView, DataReader, DataSet, DataRow, DataColumn, Array, List, SqlCommand, OleDbCommand, SqlDataAdapter, 及OleDbDataAdapter对象。

对于开发来说,最常用的还是DataView、DataReader、DataSet、DataRow、Array、List这几种类型了,有几点需要注意一下:·图表控件支持多数据源的绑定,例如:X轴绑定一个数据集ds1,Y轴可以绑定另一个数据集ds2,当然也可以是X轴绑定到一个List数据对象,Y轴绑定到一个DataView对象等等。

·图表控件的绑定方式一般有两种,常规绑定及交差表的绑定。

·图表控件的Y轴数据,支持一次绑定多个值,以绘制时间、区域、使用量等之类的图形。

绑定数据的流程如下:2008111015142478.png (44.03 K)2008-11-10 22:19:03大意是,绑定数据里面是否有分组数据需要绑定,如果有,则调用交叉表绑定的方法。

否则判断是否时绑定X轴和Y轴(包括标签、超链接、图例文字等自定义属性),如果是,则调用Points.DataBind方法进行绑定操作。

再判断是否有不同的X轴或Y轴数据,如果有,则分别调用X,Y轴的绑定方法Points.DataBindX,Points.DataBindY进行数据绑定。

最后,再判断是否需要进行多个Y轴值的绑定。

下面分别对几种数据绑定的方法进行一下说明:1.绑定一张数据表绑定一张数据表,例如绑定一张普通的数据表,表数据如下: 2008-11-10_214947.gif (3.24 K)2008-11-10 22:19:03绑定方法的代码:1. string mySelectQuery="SELECT Name, Sales FROM REPS;";2. OleDbConnection myConnection = newOleDbConnection(myConnectionString);3. OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);4. myCommand.Connection.Open();5. OleDbDataReader myReader =myCommand.ExecuteReader(CommandBehavior.CloseConnection);6. Chart1.DataBindTable(myReader, "Name");7. myReader.Close();8. myConnection.Close();复制代码因为数据源中只有两列Name和Sales,因此在调用Chart1.DataBindTable方法的时候,告诉了图表X轴的名称为Name,因此自动将Sales设置为Y轴的数据了.生成的图形如下: 2008111015495258.png (17.71 K)2008-11-10 22:19:03如果修改一下Sql语句为:SELECT Name,ID,RegionID FROM REPS;其它都不变化,再看看图表是如何处理另外两个字段的,生成的图表如下: 2008111015513437.png (16.09 K) 2008-11-10 22:19:03此时,图表自动将ID,RegionID字段当成了Y值,生成了两个Series,因此每个用户都有两个值,生成的图形也有两个柱状图.上面是一种动态绑定的方式,有人可能会问了,如果我想确定我要绑定的列,比如:X轴绑定某个字段,Y轴绑定某个字段如何操作呢?对于这种绑定,有几种方法可以实现.第一种:这种方法可能是很常见的,在原来的.NET编程中出现的机率非常之高,方法如下:1. // 设置数据源,myDv是一个取出数据集的DataView2. chart1.DataSource = myDv;3.4. // 分别设置图表的X值和Y值5. chart1.Series["Series1"].XValueMember = "Name";6. chart1.Series["Series1"].YValueMembers = "Sales";7.8. // 绑定设置的数据9. chart1.DataBind();复制代码第二种:即直接调用点的绑定方法1. //myReader为取得的DataReader对象2. Chart1.Series["Series1"].Points.DataBindXY(myReader, "Name", myReader, "Sales");复制代码第三种:调用DataBind的方法实现1. Chart1.Series["Series1"].Points.DataBind(myReader, "Name", "Sales", "");上面几种方法得到的效果都是一样的.当然了,上面三种方法需要自己建立Series,要显示两个柱状图,像上面的例子中的图形,那么得手动建立两个Series,然后分别进行上面的绑定操作。

此处说一下Label和Tooltip的绑定方式,要在绑定的图表中显示标签(Label)及提示(Tooltip),可以在绑定的时候,设置绑定的属性. 对于上面的第一、二种方法,可以调用如下的方法来设置Label和Tooltip;例如,两个数据序列名称分别为Series1和Series2,设置代码如下:1. Chart1.Series["Series1"].Label = "#VAL";2. Chart1.Series["Series1"].Points.DataBind(myDs.Tables[0].DefaultView, "Name", "ID", "");3. Chart1.Series["Series2"].Label = "#VAL";4. Chart1.Series["Series2"].Points.DataBind(myDs.Tables[0].DefaultView, "Name", "RegionID", "");其中的#VAL是Label和Tooltip的通配符,表示取默认Y轴变量的意思。

具体的详细操作可以参考例程:Chart Features/Labels下面的内容。

以后有空我也写一篇Label的和其它变量的设置吧。

对于第三种调用的绑定则稍微不同,如下:1. Chart1.Series["Series1"].Points.DataBind(myDs.Tables[0].DefaultView, "Name", "ID", "Label=ID,ToolTip=RegionID");2. Chart1.Series["Series2"].Points.DataBind(myDs.Tables[0].DefaultView, "Name", "RegionID", "Label=RegionID,ToolTip=ID");其实就是利用第三个属性,通过格式化的字符串来设置绑定属性,Label表示标签,ToolTip 表示提示信息,Url表示超链接等等。

最后生成的图片如下:2.绑定一个交叉表微软的图表控件提供了一个交叉表数据的绑定方法DataBindCrossTable,它可以根据数据动态的生成数据序列(Series),借用官方的例子,数据库的表数据如下:我们先看看DataBindCrossTable的参数,它有两个重载方法,分别是:1. public void DataBindCrossTable (2. IEnumerable dataSource,3. string seriesGroupByField,4. string xField,5. string yFields,6. string otherFields,7. PointSortOrder sortingOrder8. )以及1. public void DataBindCrossTable (2. IEnumerable dataSource,3. string seriesGroupByField,4. string xField,5. string yFields,6. string otherFields7. )每个参数的含义如下:dataSource要绑定的数据源.seriesGroupByField要分组统计的数据字段名称,例如按姓名、日期等.xFieldX轴绑定的字段名称.yFieldsY轴绑定的字段名称,如果需要绑定多个字段,则用逗号将字段名分开. otherFields其它数据字段属性,就是上面刚讲的,标签、提示、Url等属性.sortingOrder设置数据是正确还是逆序排列.此时要以统计每个用户的年销售曲线,那么分组统计的字段名应该设置为Name,如下:1. Chart1.DataBindCrossTable(2. myReader,3. "Name",4. "Year" ,5. "Sales",6. "Label=Commissions{C}");用如上的方法绑定,生成的图形如下:相反,如果要统计用户每年的曲线,则将字段反转一下即可,如下:1. Chart1.DataBindCrossTable(2. myReader,3. "Year",4. "Name",5. "Sales",6. "Label=Commissions{C}");这次就先说到这里咯,说几个需要注意的地方:在进行Y轴数据绑定的时候,如果要绑定多个字段,默认情况会出错,那是因为需要设置Y 轴的可保存值数量,设置为你需要保存的数量即可,设置的地点在:Series-》YValuesPrePoint,设置为你需要显示的个数即可。

相关文档
最新文档