在图表中,x轴代表类别,y轴代表数值(好比类与他们的属性)
这是数据库中的数据,下面我们选前5辆车,在图表中显示他们的名字,油耗,功率,价格
创建查询数据的类
class CarDA { public List < CarData> select() { List < CarData > list= null; SqlConnection conn = new SqlConnection("server=.;database=mydb;user=sa;pwd=123"); conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select top 5* from car"; SqlDataReader dr= cmd.ExecuteReader() ; if(dr.HasRows) { list = new List<CarData>(); while(dr.Read()) { CarData data = new CarData(); data = new CarData(); data.Name = dr["name"].ToString(); data.Oil=(decimal)dr["oil"]; data.Powers=dr["powers"].ToString(); data.Price=(decimal )dr["price"]; list.Add(data); } } return list; cmd.Dispose(); conn.Close(); } }
class CarData { private string _name; public string Name { get { return _name; } set { _name = value; } } private decimal _oil; public decimal Oil { get { return _oil; } set { _oil = value; } } private string _powers; public string Powers { get { return _powers; } set { _powers = value; } } private decimal _price; public decimal Price { get { return _price; } set { _price = value; } } }
窗体一加载,给图表绑定数据源,注意:绑定时以一列为单位,指明每列的x轴和y轴分别对应数据源的属性名(也就是泛型集合里面对象的属性名)。注意:指定的必须是属性名,不能是字段名,这也要求数据源的对象的字段必须封装,必须有属性。
这里体现了C#编程的封装特性,我们给chart图表工具一个数据源,让它帮我们形象的展示数据,我们并不关心到底是怎样实现的,我们只告诉它需要显示那些数据,剩下的就交给chart图表工具了。
private void Form1_Load(object sender, EventArgs e) { List<CarData> list = new CarDA().select(); if (list != null) { chart1.DataSource = list; chart1.Series["Series1"].XValueMember="name"; chart1.Series["Series1"].YValueMembers = "oil"; } }
运行结果
在Series属性里,可以设置每列的显示名字,并添加新列
private void Form1_Load(object sender, EventArgs e) { List<CarData> list = new CarDA().select(); if (list != null) { chart1.DataSource = list; chart1.Series["油耗"].XValueMember="name"; chart1.Series["油耗"].YValueMembers = "oil"; chart1.Series["功率"].XValueMember = "name"; chart1.Series["功率"].YValueMembers = "powers"; chart1.Series["价格"].XValueMember = "name"; chart1.Series["价格"].YValueMembers = "price"; } }