Search code examples
vb.netwinformschartsmschart

Column Chart - Set string labels for X axis


This must be trivial, but I cannot find anything on the net.

I have a simple datatable dtChart with 3 columns (string, int32, int32) attached as datasource to Chart1 (to a two series) and set the ints for YValueMembers. The chart displays well, so far so good, but some scale numbers bellow columns.

Chart1.ChartAreas(0).AxisX.LabelStyle.Interval = 1

Displays labels on all columns, but with zeros. When I try to set XValueMember to the first string column from dtCharts (either 1 or both series):

Chart1.Series(0).XValueMember = "ProcesName"

... then the painting of chart faisl (red rectangle with cross appears) I tried this too:

Chart1.Series(0).AxisLabel = "#VALX"

...with no progress.

How do I set labels for the X axis in a data-bound chart?

EDIT: By the way, I know I can go throu the points collection and set the labels separately for each of them, but I would consider that a workaround, not a solution. There must be a direct way to use bound column, a sort-of "DisplayMember".


Solution

  • Just drop a new chart control on the form and use such code to show data in the chart:

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        Me.Chart1.DataSource = GetData()
        Me.Chart1.Series.Clear()
        Chart1.ChartAreas.Clear()
        Chart1.ChartAreas.Add("Area0")
        Me.Chart1.Series.Add("Math")
        Me.Chart1.Series.Add("Physics")
    
        Chart1.Series(0).XValueMember = "Name"
        Chart1.Series(0).YValueMembers = "Math"
        Chart1.Series(0).IsValueShownAsLabel = True
        Chart1.ChartAreas(0).AxisX.LabelStyle.Angle = -90
    
        Chart1.Series(1).XValueMember = "Name"
        Chart1.Series(1).YValueMembers = "Physics"
        Chart1.Series(1).IsValueShownAsLabel = True
    End Sub
    
    Public Function GetData() As DataTable
        Dim dt = New DataTable()
        dt.Columns.Add("Name", GetType(String))
        dt.Columns.Add("Math", GetType(Integer))
        dt.Columns.Add("Physics", GetType(Integer))
        dt.Rows.Add("Alex", 12, 17)
        dt.Rows.Add("Richard", 19, 20)
        dt.Rows.Add("Alice", 14, 16)
        Return dt
    End Function
    

    And the result would be this chart:

    enter image description here