Zebra0.com

csharp drawing

Bar Graph for Sales

Start a new project. There are no controls in this project.

Add this code, using the lightening bolt to select the paint event.:

// Programmer: Janet Joy
// Display a bar graph for sales.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Sales
{
    public partial class Form1 : Form
    {
        int[] sales = { 25, 40, 50, 30, 20, 70, 80, 85, 90, 10, 20,45 };
        String[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jly", "Aug", "Spt", "Oct", "Nov", "Dec" };
        // Colors will repeat if necesary
        Color[] colors = { Color.DarkRed, Color.DarkOliveGreen, Color.DarkCyan, Color.CadetBlue };


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            // Get the graphics of the form.
            Graphics g = this.CreateGraphics();
            // Create a brush
            SolidBrush myBrush = new SolidBrush(Color.Black);
            // Set the top to 0 for the first row.
           int top = 0;
            // We will create a graph that is 300 pixels wide. 
            // We will make each bar in the graph proportional with the max value at 300.
            int max = sales.Max();
            float ratio = 300.0F / max;
            for(int i=0;i<sales.Length; i++)
            {
                // Set the color to black for the text.
                myBrush.Color = Color.Black;
                // Draw the name of the month.
                g.DrawString(months[i], this.Font, myBrush, 0.0F, top);
                // Set the color to the next color in array or back to 0.
                // The mod operator will give values within the rrray: 0,1,2,3,0,1,2...
                int clr = i % colors.Length;
                myBrush.Color = colors[clr];
                // Calculate the width of the box.
                int width = (int)(sales[i] * ratio);
                Rectangle myRect = new Rectangle(30, top, width, 20);
                // Draw the bar graph.
                g.FillRectangle(myBrush, myRect);
                // Switch back to Black to write on top of the bar.
                myBrush.Color = Color.Black;
                // Draw the amount of sales.
                g.DrawString(sales[i].ToString(), this.Font, myBrush, 40.0F, top);
                // Increment top for the next row.
                top += 20;
            }
        }
    }
}
To Do: Experiment!
Try reading the sales from a file (you will need lists instead of arrays).
Add a legend. Make vertical bars instead of a horizontal bars.

End of lesson, Next lesson: ListBox Manager in C#