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”等。

3、ChartType用途:返回或设置图表的类型注:设置类型后不用刷新,可以设计的时候选择属性,也可以代码中设置。

类型种类见附录。

示例:本示例中我们用了一个combox,可以在该combox选择类型,然后通过Click事件用select case语句来根据不同的选择给MSChart1的ChartType赋于不同的值来实现图表类型的改变。

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) = 6二维数组(2, 2) = 5二维数组(2, 3) = 4二维数组(2, 4) = 3二维数组(2, 5) = 2二维数组(2, 6) = 1With MSChart1.chartType = VtChChartType2dBar '类型为2d柱形图.ChartData = 二维数组()End WithWith cmb图表类型.AddItem "三维柱形".AddItem "二维柱形".AddItem "三维折线".AddItem "二维折线".AddItem "三维面积".AddItem "二维面积".AddItem "三维梯形".AddItem "二维梯形".AddItem "三维组合".AddItem "二维组合".AddItem "二维饼形".AddItem "二维XY散点".ListIndex = 0End WithEnd SubPrivate Sub cmb图表类型_Click()With MSChart1Select Case cmb图表类型.TextCase "三维柱形".chartType = VtChChartType3dBarCase "二维柱形".chartType = VtChChartType2dBarCase "三维折线".chartType = VtChChartType3dLineCase "二维折线".chartType = VtChChartType2dLineCase "三维面积".chartType = VtChChartType3dAreaCase "二维面积".chartType = VtChChartType2dAreaCase "三维梯形".chartType = VtChChartType3dStepCase "二维梯形".chartType = VtChChartType2dStepCase "三维组合".chartType = VtChChartType3dCombination Case "二维组合".chartType = VtChChartType2dCombination Case "二维饼形".chartType = VtChChartType2dPieCase "二维XY散点".chartType = VtChChartType2dXYEnd SelectEnd WithEnd Sub4、Column用途:返回或设置当前列之所以要设置当前列,是因为我们对数据操作时需要指定当前行与列,因为MSChart没有像EXCEL软件的cells(行,列).text这样指定行与列的属性。

(此处暂不确定,之后更新)注:尝试过MSChart的列数设置为65536,会溢出,设置为30000是可以的,更多就已经无响应了,行就没有试了,不过应该不会有人要这么多行与列吧示例:此示列是1个二维柱形图,我们通过将当前列设置为2,然后修改2列的数值由2变为6Private Sub Command1_Click()MSChart1.Column = 2 '将第2列设置为当前列MSChart1.Data = 6 '更改当前列的值End SubPrivate Sub Form_Load()Dim 一维数组(1 To 6)'为了表示得更清楚,我们采取逐个赋值的方法一维数组(1) = 1一维数组(2) = 2一维数组(3) = 3一维数组(4) = 4一维数组(5) = 5一维数组(6) = 6With MSChart1.chartType = VtChChartType2dBar '类型为2d柱形图.ChartData = 一维数组()End WithEnd Sub示例:对于多行的图形,同时需要指定行和列,如果未指定行(并且未有过其他操作图表的代码),会默认为第一行,未指定列,会默认为1列。

以上例的图表为例,我们要改变第2行的第2列的当前值为6Private Sub Command1_Click()MSChart1.Column = 2 '将第2列设置为当前列MSChart1.Row = 2 '将第2行设置为当前行MSChart1.Data = 6 '更改当前行、列的值End Sub用途:返回或设置图表的总列数示例中使用二维数组生成2行6列的图表,请注意看两次结果的不同之处(代码就使用之前的)下列两图形其实是一个,ColumnCount=6,之所以呈现的外观不一样,是因为设置了以下属性:MSChart1.Plot.DataSeriesInRow = True用途:返回或设置列标签示例:以2行6列的数据图表为例,通过指定当前列=1,然后设置列标签;然后再指定当前列=6,再设置列标签。

合集下载

mschart控件如何使鼠标移动到数据标记上时显示相应的内容

mschart控件如何使鼠标移动到数据标记上时显示相应的内容

mschart控件如何使鼠标移动到数据标记上时显示相应的内容在MouseMove事件中可以得到鼠标的位置,再用TwipsToChartPart方法就可以知道当前位置对应的是Chart的哪个部分。

不过,这个方法的使用不太方便。

你可以使用下面的代码:Private Sub MSChart1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)Dim whichPart As Integer, whichSeries As IntegerDim whichNumber As IntegerMSChart1.TwipsToChartPart X, Y, whichPart, whichSeries, whichNumber, 0, 0'Debug.Print whichPart, whichSeries, whichNumberLabel1.Caption = X & " " & Y & " " & whichPart & " " & whichSeries & " " & whichNumberEnd Sub你可以在某条曲线上点一下,这时整条曲线被选中,上面的代码输出的whichPart值为VtChPartTypeSeries(5),表示一个序列被选中了,whichSeries表示序列号。

如果你在这条选中的曲线的不是节点的某个位置上点一下,这时某个节点被选中,上面的代码输出的whichPart值为VtChPartTypePoint(7),whichNumber表示是序列中的哪个点,你就可以利用这些信息知道用户选择了哪个数据。

但是MSChart的这种方式对用户不是很方便。

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();}}}}。

MSChart控件

MSChart控件

MSChart控件在VB中,除了可以利用Line和Circle方法绘制几何图形外,还可以利用MSChart 控件绘制各种图表。

MSChart控件在绘制直方图(条形图)、折线图、饼图、标记图、填充区域图等各种常用的数据分析图形方面有很大的优势,我们只要将需按图形表示的数据装入数组中,然后将数组数据赋值给MSChart控件,再进行一些简单的图形标题、背景、图例、注脚方面的定义,就可以得到所期望的数据分析图形。

【教学目标】使学习者能够掌握MSChart控件的创建和使用方法。

【教学要求】掌握:定义统计图表数据源的方法。

理解:创建统计图表的过程及步骤。

掌握:MSChart控件的相关属性定义方法。

【本节重点】创建统计图表的过程及步骤。

一、MSChart控件MSChart控件的系统默认名是:MSChart1、MSChart2等。

由于MSChart控件不是VB内建的基本控件,因此在使用前必须用工程菜单中的“部件”,添加MSChart控件。

添加MSChart控件的选项是“Microsoft Chart Control 6.0(OLEDB)”。

当我们在VB的工具箱中添加了MSChart控件,并在窗体中“画”出MSChart控件后,可见到如下图形:图:7.3二、设置MSChart系列数据与图表类型1、MSChart的系列通过对图7.3的分析,我们可以看到MSChart图表中将数据分组显示。

如图中R1、R2、R3、R4、R5各代表一个组,一组相关的数据在绘图中称为一个“系列”,一张图表可由一个或多个系列构成。

若MSChart控件被赋值一个一维数组数据,则它所显示的数据图形只绘制出一个系列的图表。

若一维数组中的数据被绘制为直方图,则数组中的数据会被逐一绘制为直方图中的彩条。

若一维数组中的数据被绘制为圆饼图,则数组中的数据会被逐一绘制为饼图中的彩色扇形。

若MSChart控件被赋值一个二维数组数据,则它所显示的数据图形将绘制出多个系列的图表。

c#mschart控件使用方法

c#mschart控件使用方法

c# ms chart 控件使用方法第一个简单的chart:spline// Create new data series and set it's visualattributes 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 attributesSeries 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 dateDateTime 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.AddX Y(rnd.Next(10,90), // X value is a daternd.Next(40,50)); //Close Y value}数据库数据,datetime-int类型string connStr ="server=localhost;database=seis_project;uid=seisprjs;pwd=seisprjs";SqlConnection myConn = new SqlConnection(connStr);string selStr = "select 时间,序号from pub_log_read order by 序号asc";SqlCommand myCmd = myConn.CreateCommand();mandText = selStr;myConn.Open();SqlDataReader sdr =myCmd.ExecuteReader(CommandBehavior.CloseConnection);// Since the reader implements and IEnumerable, pass the readerdirectly into// the DataBindTable method with the name of the Column to be usedas the X ValueChart1.DataBindTable(sdr, "时间");sdr.Close();myConn.Close();数据库数据2,string-int类型string connStr ="server=localhost;database=seis_project;uid=seisprjs;pwd=seisprjs";SqlConnection myConn = new SqlConnection(connStr);string selStr = "select 帐号,count(帐号) as 次数from pub_log_read groupby 帐号order by 帐号asc";SqlCommand myCmd = myConn.CreateCommand();mandText = selStr;myConn.Open();SqlDataReader sdr =myCmd.ExecuteReader(CommandBehavior.CloseConnection);// Since the reader implements and IEnumerable, pass the readerdirectly into// the DataBindTable method with the name of the Column to be usedas the X ValueChart1.DataBindTable(sdr, "帐号");sdr.Close();myConn.Close();数据库绑定3-error?string connStr ="server=localhost;database=seis_project;uid=seisprjs;pwd=seisprjs";SqlConnection myConn = new SqlConnection(connStr);string selStr = "select 帐号,count(帐号) as 次数from pub_log_read groupby 帐号order by 帐号asc";SqlCommand myCmd = myConn.CreateCommand();mandText = selStr;myConn.Open();// Set chart data sourceChart1.DataSource = myCmd;// Set series members names for the X and Y valuesChart1.Series["Series1"].X ValueMember = "帐号";Chart1.Series["Series1"].YValueMembers = "次数";// Data bind to the selected data sourceChart1.DataBind();myConn.Close();数据库4,只绑定ystring connStr ="server=localhost;database=seis_project;uid=seisprjs;pwd=seisprjs";SqlConnection myConn = new SqlConnection(connStr);string selStr = "select 序号from pub_log_read order by 序号asc";SqlCommand myCmd = myConn.CreateCommand();mandText = selStr;myConn.Open();SqlDataReader sdr =myCmd.ExecuteReader(CommandBehavior.CloseConnection);// Since the reader implements and IEnumerable, pass the readerdirectly into// the DataBindTable method with the name of the Column to be usedas the X ValueChart1.Series[0].Points.DataBindY(sdr);sdr.Close();myConn.Close();数据库5,绑定xystring connStr ="server=localhost;database=seis_project;uid=seisprjs;pwd=seisprjs";SqlConnection myConn = new SqlConnection(connStr);string selStr = "select 帐号,count(帐号) as 次数from pub_log_read groupby 帐号order by 帐号desc";SqlCommand myCmd = myConn.CreateCommand();mandText = selStr;myConn.Open();SqlDataReader sdr =myCmd.ExecuteReader(CommandBehavior.CloseConnection);// Since the reader implements and IEnumerable, pass the readerdirectly into// the DataBindTable method with the name of the Column to be usedas the X ValueChart1.Series[0].Points.DataBindX Y(sdr, "帐号",sdr,"次数");sdr.Close();myConn.Close();数据库6,支持显示参数// 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 REPSALES WHERE Year=2004;";// 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();// Create adatabasereaderOleDbDataReader myReader=myCommand.ExecuteReader(CommandBehavior.CloseConnection);// Since thereader implements and IEnumerable, pass the reader directlyinto// theDataBind method with the name of the Columns assigned to theappropriateproperty Chart1.Series["Series1"].Points.DataBind(myReader,"Name","Sales","Tooltip=Year, Label=Commissions{C2}");// Closethe reader and the connectionmyReader.Close();myConnection.Close();数据库7,支持多line// 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 REPSALES;";// 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();// Create adatabasereaderOleDbDataReader myReader=myCommand.ExecuteReader(CommandBehavior.CloseConnection);// Data bindchart to a table where all rows are grouped in series by the "Name"column Chart1.DataBindCrossTable(myReader,"Name","Year","Sales","Label=Commissions{C}");// Closethe reader and the connectionmyReader.Close();myConnection.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.AddX Y(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 X ML 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 X MLschema into the DataSet.custDS.ReadX mlSchema( fileNameSchema );// ReadX ML schema and data into the DataSet.custDS.ReadX ml( 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 X value. 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 DataBindX Y methodChart1.Series[0].Points.DataBindX Y(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.DataBindX Y(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.DataBindX Y(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.AddX Y(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"].I sX ValueIndexed = 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.DataBindX Y(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();}}}}。

mschart安装使用

mschart安装使用

mschart安装使用最近需要为程序显示一些柱状图、线图之类的,查了一下微软的mschart不错,功能强大。

可是自vc6.0之后mschart控件就从ms的IDE里去掉了,如果用只能自己下载安装。

安装mschart需要1 .net framewrok 3.5 sp1(注意是sp1),没有安装的话就去下载吧,完整包大概200多M2 安装MSChart.exe MSChart_VisualStudioAddOn.exe 下载mschrt20.ocx 到C:\WINDOWS\system32目录下。

命令行运行regsvr32 mschrt20.ocx注册控件3 在vs2005之后的平台上,你要么在class view下add class->MFC Class f rom ActiveX Control然后有两个,你可以选择registy然后选择ms mschart 6.0(o led),这样只能出现一个类CMSCHART,或者选择File然后浏览mschrt20.ocx,这里面生成了很多类,你全部添加进去,最后就可以用了。

第二、你可以在一个MFC dialog上insert axtivex control或者toolbox选择choose item->com选择组件让它出现在工具箱中,这样也可以有控件。

我们自己选择生成的很多类,跟网上有示例的类函数名称上有所不同,可能会给使用带来麻烦。

其实最简单的就是找到一个Demo把里面相关的CMSCHART和其它相关的十几个类都拷贝到我的工程文件夹里,再添加进来,就ok了。

网上很多例子可供参考,比如:/document/viewdoc/?id=9 59关于遇到的一些问题。

在设置图形类型的时候,m_chart.SetChartType(1|2);显示出2D曲线图,而我们用m_chart.SetChartType(16);的时候如果你只设置了m_chart. SetColumnCount(1); 就不会显示,因为16的散列图需要的是一对坐标点,你至少需要设置m_chart.SetColumnCount(2);为2。

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的元素组成最常用的属性包括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的使⽤⽅法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控件是⼀个功能强⼤的⾼级图表⼯具,拥有丰富的图表绘制功能,⽤它来可以显⽰⼆维和三维的棒图、区域图、线形图、饼图等多种常⽤图表。

ASPNETMVC中使用MsChart制作图

ASP NET MVC 中使用MsChart制作图 MVC 中使用MsChart制作图表(附实例)000微软新发布的图表控件MSChart,依赖于.NET Framework3.5 sp1的环境,制作出的图表非常漂亮。

同时,支持webfrom,winform,MVC。

本文主要介绍在ASP .NET MVC 下如何使用MSCHART制作图表。

1.下面简单列举一下MSCHART的部分图表类型2维堆积饼状图2维面积图2维气泡图2维线性图二维柱状图三维饼状图三维面积图三维线性图2. 在 MVC 框架下,如何使用MSCHART.首先看效果柱状图饼状图下面介绍使用MsChart制作图表实现的步骤:首先修改web.config 1. 将控件的命名空间加到("<system.web><pages><controls>" ) : <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Chartin g"assembly="System.Web.DataVisualization,Version=3.5 .0.0,Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> 2. 添加一个httpHandler ("<httpHandlers>"下面) :<add path="ChartImg.axd" verb="GET,HEAD"type="System.Web.UI.DataVisualization.Charting.Cha rtHttpHandler,System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>3. 然后根据自己的需要,绘制不同的图表。

微软图表控件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轴上显示标签。

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