MSChart控件教程
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控件在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# 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控件这些内容是在学习过程中进行的整理,由于感到书籍资料或软件帮助中有时让人很不容易理解,特制作这个教程,以方便其他朋友学习,从新学习此控件的人的角度来描述相应的属性,相信也能让跟我一样程度的人更容易理解,可能在学习的过程中对某些属性与方法有理解不正确,请各位指正。
附录: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安装使用最近需要为程序显示一些柱状图、线图之类的,查了一下微软的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控件的安装及应用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使用指南

微软图表控件MsChart使用指南昨天在网上看到了微软发布了.NET 3.5框架下的图表控件,第一时间抓下来看了一下,发觉功能很强劲,基本上能想到的图表都可以使用它绘制出来,给图形统计和报表图形显示提供了很好的解决办法,同时支持Web和WinForm两种方式,不过缺点也比较明显,只能在最新的开发环境中使用,需要.Net 3.5 Sp1以及VS 2008的开发环境。
下面是下载地址:mework 3.5)–1.包含英文版,中文版。
上面提供的链接是中文版的,可以更改为英文版。
2.语言包:Microsoft Chart Controls for Microsoft .NETFramework 3.5 Language Pack3.Microsoft .NET Framework 3.5 的Microsoft 图表控件的语言包,包含23中语言。
4.Microsoft Chart Controls Add-on for Microsoft Visual Studio 2008–这个只有英文的,没找到中文的。
5.文档(Microsoft Chart Controls for .NET Framework Documentation)–这个只有英文的,没找到中文的。
6.WinForm 和的例子(Samples Environmentfor Microsoft Chart Controls)–这个只有英文的,没找到英文的。
7.Demo 下载:/mschart下了它的示例程序后,运行了一下,非常的强大,可以支持各种各样的图形显示,常见的:点状图、饼图、柱状图、曲线图、面积图、排列图等等,同时也支持3D样式的图表显示,不过我觉得最有用的功能还是支持图形上各个点的属性操作,它可以定义图形上各个点、标签、图形的提示信息(Tooltip)以及超级链接、Jav ascript动作等,而不是像其它图形类库仅生成一幅图片而已,通过这些,加上微软自己的Ajax框架,可以建立一个可以互动的图形统计报表了。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
MSChart控件这些内容是在学习过程中进行的整理,由于感到书籍资料或软件帮助中有时让人很不容易理解,特制作这个教程,以方便其他朋友学习,从新学习此控件的人的角度来描述相应的属性,相信也能让跟我一样程度的人更容易理解,可能在学习的过程中对某些属性与方法有理解不正确,请各位指正。
附录:1、AllowDynamicRotation返回目录作用:返回或设置是否可旋转图表注:需要图表的ChartType是3d类型才可以,当AllowDynamicRotation=True时,在图表中可按住ctrl+鼠标左键旋转图表。
示例:F列代码在窗体加载时将MSChartl设置为3d柱形图,并允许按住ctrl+鼠标左键旋转。
(窗体上放一个MSChart控件)Private Sub Form_Load()With MSChart1.chartType = VtChChartType3dBar '类型为3d柱形图,类形常数详见附录.AllowD yn amicRotati on =True '允许旋转End WithEnd Sub口ForniilA■AllowDynamicRotation 值: 下列代码将以对话框的形式返回上面示例的MsgBox MSChart1.AllowDy namicRotati onTrue2、ChartData返回目录注:书中及软件帮助文档中说到数组需要变体型数值,是指如果要将数组第一个元素作为标题,其他作为数据,那个这个数组既有字符又有数字,那么就需要一个变体形。
如果数组中并不包含标题(或是之后使用属性来赋于标题),那么数组是可以定义类形的,个人建议先给定数组类型,之后再使用属性来设置标题。
作用:设置:将一个数组的数据作表图表的显示数据返回:将图表数据赋给一个数组示例:将数组元素作为图表的显示数据制作一个1行6列的的图表(数组的维代表图表的行,每维的元素代表列)Private Sub Form_Load()Dim 一维数组(1 To 6) '为了表示得更清楚,我们采取逐个赋值的方法一维数组(1)= 1一维数组(2) = 2一维数组(3) = 3一维数组(4) = 4一维数组(5) = 5一维数组(6) = 6With MSChartl.chartType = VtChChartType2dBar '类型为3d 柱形图.ChartData = 一维数组()End WithEnd SubEnd SubComm aitdl为了理解图表的行列与数组的维数的对应关系,再举例一个二维数组(图表对应就形成Private Sub Form_Load()Dim 二维数组(1 To 2, 1 To 6) '为了表示得更清楚,我们采取逐个赋值的方法 二维数组 二维数组 二维数组 二维数组 二维数组 二维数组With MSChart1.chartType = VtChChartType2dBar '类型为 2d 柱形图 .ChartData =二维数组()End With导 Forml—r 65 4 3 2 ft54=1= 3-I- 22行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) = 6导Formlill--5--4…3--2R1R2CommaitdlF面是将数组的第一个元素设置成字符,使图表加载时将其作为标题的示例: 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)(2, 3)(2, 4)(2, 5)(2, 6)"第二行标题”54With MSChart1.chartType = VtChChartType2dBar '类型为2d 柱形图.ChartData =二维数组()End WithEnd Sub口Forinl—r t.M一维翹1行1列12列 2 -3列34列45列56列 6 =上述例子是将数组的内容反应到图表中,下面我们将使用上面的一维和二维图表,从图表中获得数据给数组,并将 数组显示出来以验证结果(我们采取设置一个断点,然后通过视图 本地的方式来查看生成的数组):Cl Fermi库工程2 -Fpn^l (Co«3r) TJfe |Caw4udl II Ci-m vndl tripag 5*ih f :OTundl diet 0 U L * 别jft 加 0 ■ II TriT^abe Sih farrjj^sdl < 』L* 二璀T)细a [« 2, J It 6) (2 1;7邯亡¥更舌跟『血眸总匹刚iDtf 出盘 净駅■ 诩工 __®x 二■¥池AC 」 ]■] £■] 31■0 b] 1. 1?3 4-s 6 & c - 4- ..M L " .4 灯和匸三 贼liZJiulTjrfJB* 如尤M 卅主总国I 工程L P M .I I ^iiif.ardl jni ck裹乜式~ 【诅 曰祈魏用 -轉地(0呈僮 -邓fttUbcr -瞪细yea ” -■SMnrcs" L 證趙心怔「 S'Mft) -谿用O 沖「 -(I ] -Jii 欄 ws -HSlifllLS -斬畑Id -5m tL^ L 融^8(沁 幻弓f 檢1笙〕 -iiOfes -¥的论q -iisoes -険fiI2E L I 现1 —三 y^pii/y^rrhi —' ^iTi snt [Dio?. XoTi ant 血 to 6J 『也■'“ Vtzi vbt/ftTin ( Vu-1 ub/Etran^ Kari HiiLr'Elxirii Y HJ i 袒".丿悅站5『喘 ¥«■* Mlt/WtT 山匸 Mri 皿t/Str i 口耳 Ku-i uiL O J to b. VuTh 4iir/Slr jci^ ¥«■* 曲咲 苜xi 皿cyDabl. KiTi EttryLittle Vayi^nr/D-.l.l- ViTi tnLf^Dnrjbl* Fari 『廿■ »匕(D I.U ft. Vtri uit/ftTicif tnLf^DnrjBl^ Xtri uiLr'DgbL. ^4ThULL/Dr-j1iLrVu-i 也韶 BmM* ■如■! anLf^D^jlil* Xtri Hfi. JDebL* — 从图中可以看到,对于我们用 2给数组生成的图表,再赋给新的数组时,数组变成了素用来存储行标签,既“ RT'、“ R2”,多出来的一维用来存储列标签,既“ 3维,并且每维还多了一个元 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,2)二维数组 二维数组 二维数组 二维数组 二维数组(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 Sub3456(1.3) (1.4) (1.5) (1.6)Private 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 SubQ- Forml耳亘亘I£1E22图表类型:pswCemnandl经过测试,ChartType值使用数值也可以,不过一般不建议使用数值,这样更不容易理解;对应数值如下:VtChChartTy pe3dBar 3D条形图0VtChChartTy pe2dBar 2D条形图 1VtChChartT yp e3dL ine 3D折线图 2VtChChartT yp e2dL ine 2D折线图 3VtChChartT yp e3dArea 3D面积图 4VtChChartT yp e2dArea 2D面积图 5VtChChartTy pe3dSte p 3D阶梯图 6VtChChartTy pe2dSte p 2D阶梯图7VtChChartT yp e3dCombi natio n 3D组合图8VtChChartT yp e2dCombi natio n 2D组合图9VtChChartT yp e2d Pie 2D饼图14VtChChartTy pe2dXY 2D XY散点图161 r4、Column返回目录I用途:返回或设置当前列之所以要设置当前列,是因为我们对数据操作时需要指定当前行与列,因为MSChart 没有像EXCE 软件的cells(行,列).text 这样指定行与列的属性。