BLOG.CSHARPHELPER.COM: Use Label controls to make a simple bar chart in C#
Use Label controls to make a simple bar chart in C#
At design time, the program's form contains a series of value labels and bar chart labels named lbl1, lbl2, etc. These are aligned above the corresponding value labels and all of them are near the bottom of the form.
When the program starts, it uses the following code to generate some random data and display it in a bar chart.
// Make some data. private void Form1_Load(object sender, EventArgs e) { // Make the values. Random rand = new Random(); const int num_values = 100;
// Array version. int[] values = new int[num_values]; for (int i = 0; i < num_values; i++) { values[i] = rand.Next(1, 7) + rand.Next(1, 7); }
// Make a simple histogram. Label[] labels = { lbl2, lbl3, lbl4, lbl5, lbl6, lbl7, lbl8, lbl9, lbl10, lbl11, lbl12 }; int bottom = lbl2.Bottom; foreach (Label lbl in labels) lbl.Height = 1; const int pixel_scale = 10; for (int i = 0; i < num_values; i++) { int index = values[i] - 2; labels[index].Height += pixel_scale; } foreach (Label lbl in labels) { lbl.Top = bottom - lbl.Height; } }
The program first uses a Random object to create some random values between 2 and 12. The code next builds an array to hold the bar chart Label controls. It loops through the labels setting each one's Height to 1.
Next the code loops through the values incrementing the Height of the corresponding Label by 10. For example, if a value is 9, the code adds 10 to the 9th bar chart label.
The code finishes by looping through the bar chart labels setting their Top properties so they all line up on the bottom.
Comments