Fred Fred - 1 year ago 217 Question

how to draw line graph using listbox values

I was looking for the answer to my question but all codes I tried didn't work for me so I decided to ask for help.
I am newbie with making charts in and my boss wants results (by yesterday) so I don't have time to dig deeper into how to make charts.

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

Dim a As Double
Dim b As String
b = RichTextBox1.Text
a = Convert.ToDouble(b)
' Chart1.(RichTextBox1.Text)
'Convert.ToInt32(b, 0)
Chart1.DataSource = RichTextBox1.Text

'Chart1.Series("Series1").YValueMembers = b


End Sub

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

End Sub

I would like to draw a line graph.
I have a listbox with 10 numbers and a button. I would like to make a line chart from those numbers.

I also tried to use richtextbox instead of the listbox but no luck.
I would like to get something like the attached picture.

Thank you so much for help.
sample made in excel

Answer Source

--Update--- Replace this part in the Points region of code provided below

   Dim x2 As Integer = 0 ' Keep a track of index
   For Each i As Integer In ListBox1.Items
        ' create a Point with index as x and the actual value of list item as y
         s.Points.AddXY(Convert.toDouble(x2), Convert.toDouble(i))
         x2 = x2+1

A chart should be something like this

 Chart1.Series.Clear() 'Empty your chart of any previous values

 Chart1.Titles.Add("My Line chart") 'Add a Title

 Dim s As New Series 'Create a new series
 s.Name = "My Line" 'Series name

 s.ChartType = SeriesChartType.Line 'Chart type

 'Most important part, the points to plot
 'Points START
  s.Points.AddXY(1, 2)
  s.Points.AddXY(3, 4)
  s.Points.AddXY(5, 9)
 'Points END

 'Add the series to the Chart1 control

I'm not sure why you are using a RichTextBox1. If you are gathering user input (x,y) points then you will need to construct your points. Use a TextBox control instead of RichText, it should suffice, with the given description.

Replace the Points bit in the above code with this

'Assume the user is entering value/numbers separated by ","
'Use the input as both x and y
'e.g 1,2,3,...
Dim textCont As String = TextBox.Text
Dim boxValues As String() = textCont.Split(New Char() {","})
For Each item In boxValues
 s.Points.AddXY(Convert.toDouble(item), Convert.toDouble(item))
 s.Points.AddXY(Convert.toDouble(item), Convert.toDouble(item))
 s.Points.AddXY(Convert.toDouble(item), Convert.toDouble(item))

As far as the code you've provided, there is no ListBox control or reference to use in this example.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download