You are on page 1of 9

Data Binding Microsoft Chart Control

RATE THIS

Alex Gorev
20 Feb 2009 9:42 PM

32

Overview
When you add a new visualization in your application, the very first thing you do, is bind it to the
data. Microsoft Chart control allows many different ways of populating data in the chart and it is
important to understand the differences between them and being able to choose the best
approach. I put together all the possible data binding options and the scenarios when they should
be used.

Data Sources
Before jumping into the binding methods I want to quickly list all the supportable data sources
which can be used in chart binding methods. Keep in mind that not all methods accept all source
types.

SqlCommand

OleDbCommand

SqlDataAdapter

OleDbDataAdapter

DataView

DataSet

DataReader

List

Array

IList

IListSource

IEnumerable

When you displaying categories on the X axis. starting from the most basic methods proceeding to more advanced. All data binding methods will automatically detect the type of the data and you should not worry about it. or it is not set.  Automatic series creation. tooltips and others. based on the number of columns in the data source.Defines location of the data point along X axis. Each data point in the series should have it's Y value set and in addition to the Y value you can also bind or set other data point properties:  X Value .Chart types like Bubble or Stock require multiple Y values.  All series have same X value. they are stored in the AxisLabel property of the data point. . if you want to use those values for labels or tooltips.  No multiple Y values per series. data point index in the series will be used.DataBindTable  Simple binding for X and Y values. You can also bind additional Y values in the regular chart types.  Additional Y Values . Binding Options Overview This table lists data binding techniques.  Other Properties . Chart.  Category .  No binding for extended chart properties like tooltips. If not specified.Data Point X and Y values When you bind chart you create series and series data points.Some of the binding methods allow you to set additional properties like data point labels.

DataBind  Can be used at design-time.  Automatically creates series for each unique value in specified column used to group the data.DataBindCrossTab .Chart. Points.  Supports multiple Y values.  No binding for extended chart properties like tooltips. plus:  Supports binding for extended chart properties like tooltips.DataBind(X)Y Points.  Does not support different data sources for X and Y values of a series.  Only single level grouping is supported. including separate data source for X and Y values.  Supports multiple Y values.  Provides more flexibility than methods above  Same as the above.DataBind Chart.  Supports multiple data sources.  No binding for extended chart properties like tooltips.DataSource and Chart.

New series will be automatically created for each of the columns and you can optionally use one column for the X value for all series.DataBind() method.Binding Options Details Chart. Prod D. // Set chart data source chart1. Prod C. Example Imagine you have a data source containing these columns: Prod A. Multiple Y values can be bound if you specify comma separated list of members in the YValueMembers property. Prod B. You can force chart to bind at any moment by calling Chart. Other and SalesName.DataBindTable method is the simplest way to bind chart to a table with several columns. Chart will automatically bind itself to specified data source and members just before rendering.DataSource = myCommand. "SalesName"). Chart. Prod E.DataSource property Chart DataSource property is the only way to bind chart at design-time. you can easily create chart below with a single line of code: Chart1. In addition to specifying the DataSource property you also need to create series and set their YValueMembers and optionally XValueMember properties.DataBindTable(myReader.DataBindTable method The Chart. // Set series members names for the X and Y values .

Example In the sample below we have a table that has the sales and commissions of sales people for three years. The X values are bound to the "Year" column. Each unique value in the specified grouped column results in the creation of a data series. in that it allows for the grouping of unique values in a column. and the LegendText property is bound to the "Name" column. the Label property of the resulting data points (one per record) is bound to the "Commissions" column. the Y values are bound to the "Sales" column. In addition. Label. DataBindCrossTab The Chart. extended data point properties other than X and Y values can be bound.DataBindCrossTab is different compared to all other binding methods. LegendText. A list of these properties are as follows: AxisLabel. chart1. These other properties are bound using the otherFields parameter using this syntax: PointProperty=Field[{Format}] [.XValueMember = "Name". We group by the "Name" column.PointProperty= Field[{Format}]]. . For more information on possible formats see the Formatting Types topic in the MSDN library.Series["Series 1"]. // Data bind to the selected data source chart1.Series["Series 1"].DataBind().YValueMembers = "Sales".chart1. thereby creating one data series per sales person. LegendTooltipand CustomPropertyName (t he name of a custom property). Tooltip.

LegendText. "Name".DataBind( myReader.Points. chart1.DataBind This method allows for data point properties other than X and Y values to be bound to data columns. Tooltip. This method does not allow you to specify separate data sources for the X and Y values of a series (for this functionality use the DataBind(X)Y methods described in the section above).Series["Series1"]. . LegendTooltip andCustomPropertyName ( the name of a custom property). Y values to "Sales". you want to set data point label to a value in one of the data source columns. These other properties are bound using the otherFields parameter using this syntax: PointProperty=FieldName[{Format}][. "Tooltip=Year. "Sales". "Sales". The Label and Tooltip properties of the resulting data points are also bound to the "Commissions" and "Year" column. // and Label property to "Commissions. Label. Chart1. Example Code below demonstrates how to bind X and Y values of the series to columns "Name" and "Sales" respectively. "Name". "Year".PointProperty= FieldName[{Format}]] A list of these properties includes: AxisLabel. For example.// Group by "Name" column. Points.DataBindCrossTab(myReader. bind X values to "Year". "Label=Commissions").

0}.4. OleDbDataReader may have access to more than one column of data. Example // Resolve the address to the Access database string fileNameString = this. fileNameString += ". then the first available column will be used. If the column to be used is not specified.DataBindY(array).Series["Series1"].\\. Some data sources support multiple values (e. 8.3.g.\\data\\chartdata.. 5. 3. Example Code below demonstrates how to bind series points to the array of doubles. 1.0. data sources that have columns of data).MapPath(". // Initialize an array of doubles. 9.3.4. For example.mdb". 4.8. 6.OLEDB.6.2. 7. Chart1.Data Source=" + fileNameString. . while DataBindY binds Y values only. you can always 'manually' bind chart by iterating through the data source and add data points to the series as needed. When binding X and Y values using DataBindXY the same or different data sources may be used. Note that when specifying the column names to be bound to the Y values a comma can be embedded as part of a column name by specifying a double comma... To use a column other than the first one just specify the column name in the method call. Points. double [] array = { 2.Points.Jet. This approach is also very useful when series data is calculated using some formula. // Bind the double array to the Y axis points of the data series. 'Manual' series population In case you need to perform some custom actions while binding and none of the above methods works.6."). // Initialize a connection string string myConnectionString = "PROVIDER=Microsoft.Label=Commissions{C2}").5.DataBind[X]Y The DataBindXY method allows for the binding of X and Y values of a series.\\.

// Create a database command on the connection using query OleDbCommand myCommand = new OleDbCommand(mySelectQuery.Open().BorderWidth = 2.SelectCommand = myCommand.Add(seriesName).Series[seriesName]. int YVal = (int) row[columnName].Tables["Query"]. // Initializes a new instance of the OleDbDataAdapter class OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(). YVal).". // Initializes a new instance of the DataSet class DataSet myDataSet = new DataSet(). Chart1.ChartType = SeriesChartType.Line.Tables["Query"]. foreach(DataRow row in myDataSet. // Create a database connection object using the connection string OleDbConnection myConnection = newOleDbConnection(myConnectionString). colIndex < myDataSet.DataSource = myDataSet.Count.Fill(myDataSet. // Open the connection myCommand. "Query").Rows) { // For each Row add a new series string seriesName = row["SalesRep"]. Chart1.ColumnName. } } DataGrid. .AddXY(columnName. // Adds rows in the DataSet myDataAdapter.Points.Tables["Query"].Columns[colIndex].Connection.Series[seriesName]. colIndex++) { // For each column (column 1 and onward) add the value as a point string columnName = myDataSet.Series.Columns. myDataAdapter.ToString(). for(int colIndex = 1.// Define the database query string mySelectQuery="SELECT * FROM SALESCOUNTS.Series[seriesName]. Chart1. myConnection). Chart1.

Understand what empty points are and how you can use them. myCommand. Find more information in the documentation and Chart Sample Environment. // Closes the connection to the data source.DataBind(). This is the preferred // method of closing any open connection.If you are using a stacked chart type with categorical X axis this helper method can be very useful.Connection.Close().DataGrid. Right now the best source of the information is Chart Sample Environment but I will blog about it later. Other useful things to know Here are couple things that you should know about when binding chart:  Empty Points . .  AlignDataPointsByAxisLabel .