Click here to Skip to main content
Click here to Skip to main content

Creation of a Simple C# Program: List Keeper (File I/O, Text Scrolling, Task Object)

By , 5 Sep 2012
Rate this:
Please Sign up or sign in to vote.

Introduction

I recently put together a small application for a colleague. He requested a simple application that he could use to maintain a price list of multiple items. He also requested the ability to scroll a price list in large font at different speeds. Using System.IO and System.Threading.Tasks, I hacked together a quick, simple application. Here, I would like to share the source code with you.

Using the code

To compile and run the code immediately:

  1. Save the source code file locally as a .cs file.
  2. Using a .NET compiler (csc.exe) version 4 or later, compile the source code.
  3. Save the inventory file as "samplescrap.csv" without quotes to the same folder location as the compiled EXE.

Failure to follow these steps will result in the application not working.

The application opens a file, reads from a file, scrolls the file contents across the form, and allows the user the ability to modify the file contents.

Using your IDE, you can create a new C# application. The new application will create a default form and some code-behind for you.

Before digging into the code-behind file, create a CSV or XLS file with two columns titled Item Description and Item Price. Enter your inventory data (sample data). If you don't want to create your own sample inventory data file, you can use a sample file that I created called "SampleScrap.csv". Feel free to download and use it from here.

When the code is started, it takes the data and loads it line-by-line to a listbox. The user can click on an item on the list box - this action causes the item to be populated into editable textboxes (txtItemDescription, txtItemPrice). Once edits are made, the user can update the file (and listbox) by clicking the Update button (cmdUpdateList).

On the scrolling tab of the application, the user can scroll the entire contents of the file by clicking a button. The scrolling speed can be changed up or down by clicking the appropriate button.

/*
 * User: ghost
 * Date: 8/28/2012
 * Time: 7:42 PM
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace List_Keeper
{
    public partial class MainForm : Form
    {
        public string ItemPrice { get; set; }
        public string ItemDescription { get; set; }
        public delegate void ScrollTextboxCallback(string delegatemethod);
        public static int ScrollSpeed = 900;
        public static bool infiniteloop = true;
        public bool Looper { get; set; }

        public MainForm()
        {
            InitializeComponent();
            StreamReader point64reader = new StreamReader(
              System.Environment.CurrentDirectory + "\\samplescrap.csv");
            try {
                do {addListItem(point64reader.ReadLine());}
                while (point64reader.Peek() != -1);
                }
            catch {
                addListItem("empty file");
            }
            finally {
                point64reader.Close();
            }
            lblScroll.Text = "Scroll speed: " + ScrollSpeed;
        }
        private void addListItem(string value)
        {
            this.listBox1.Items.Add(value);
        }        
        void listBox1Click(object sender, EventArgs e)
        {
            var ItemArray = this.listBox1.SelectedItem;
            var SingleItem = this.listBox1.SelectedItem.ToString().Split(new char[] {','});
            ItemPrice = SingleItem[0];
            ItemDescription = SingleItem[1];
            this.txtItemDescription.Text = ItemPrice;
            this.txtItemPrice.Text = ItemDescription;
        }        
        void cmdUpdateListClick(object sender, EventArgs e)
        {
            StringBuilder newFile = new StringBuilder();
            string temp = "";
            string[] file = File.ReadAllLines(
              @System.Environment.CurrentDirectory + "\\samplescrap.csv");
            foreach (string line in file)
            {
                if (line.Contains(ItemPrice + "," + ItemDescription))
                {
                    temp = line.Replace(ItemPrice + "," + ItemDescription, 
                           this.txtItemDescription.Text + "," + this.txtItemPrice.Text);
                    newFile.Append(temp + "\r\n");
                    continue;
                }
                newFile.Append(line + "\r\n");
            }
            File.WriteAllText(@System.Environment.CurrentDirectory + 
                 "\\samplescrap.csv", newFile.ToString());
            this.listBox1.Items.Clear();
            StreamReader point64reader = new StreamReader(
                  System.Environment.CurrentDirectory + "\\samplescrap.csv");
            try {
                do {
                    addListItem(point64reader.ReadLine());
                }
                while (point64reader.Peek() != -1);
                }
            catch {
                addListItem("empty file");
            }
            finally {
                point64reader.Close();
            }        
        }
        void BtnStartScrollClick(object sender, EventArgs e)
        {
            Task task = Task.Factory.StartNew(ScrollTextBox);
        }
        private void ScrollTextBox()
        {
              string tempChar = string.Empty;
              string newText = string.Empty;
              StringBuilder newFile = new StringBuilder();
            string temp = "";
            string[] file = File.ReadAllLines(@System.Environment.CurrentDirectory + 
                            "\\samplescrap.csv");
            temp = string.Join("        ", file);
            temp = temp.Replace("\"", " ");
            newText = temp;  
            this.Looper = true;
              while (this.Looper==true)
              {
                  if ( infiniteloop!=true) { break; }                  
                  tempChar = newText.Substring(0,1);
                 newText = newText.Remove(0,1) + tempChar;
                 txtScroll.Invoke(new ScrollTextboxCallback(this.UpdateTextBox), new object[] { newText });
                 Thread.Sleep(ScrollSpeed);
            }
        }        
        private void UpdateTextBox(string m_text)
        {
            txtScroll.Text = m_text;
        }        
        void BtnExitClick(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }        
        void BtnScrollFasterClick(object sender, EventArgs e)
        {
            this.Looper = false;
            ScrollSpeed = ScrollSpeed - 50;
            if (ScrollSpeed < 0) {ScrollSpeed = 0;}
            txtScroll.Text = "";
            lblScroll.Text = "Scroll speed: " + ScrollSpeed;
        }        
        void BtnScrollSlowerClick(object sender, EventArgs e)
        {
            this.Looper = false;
            ScrollSpeed = ScrollSpeed + 50;
            txtScroll.Text = "";
            lblScroll.Text = "Scroll speed: " + ScrollSpeed;
        }

    }
}

Points of Interest

  1. Breaking the infinite loop: While creating the "scroll loop" (while true), it was very easy to make it an "infinite loop" and continue scrolling forever. This becomes a problem when the user wants to change the speed of the scrolling and the infinite loop just keeps looping! To fix this, I have to tell the infinite loop when a good time to stop is. I added Looper. When the user changes the scrolling speed, scrolling is halted because Looper is set to false and the infinite loop stops.
  2. Special note - Scrolling bug: I noticed some unusual scroll behavior with this program. It appears to work as designed on (at least) two machines, however, it does not work on other machines! I am doing some research to find out the root cause of the problem. Here's what I noticed so far: The file reading/writing works as expected on all machines. The scrolling thread only works on some machines, but not all. I'm still unsure of the root cause of this (32-bit vs. 64-bit?). As soon as the bug is figured out, I will update this article. Questions, comments, feedback is welcome.
  3. .NET version 4.0 or later is critical when compiling the code because the Task object does not exist in earlier versions for the .NET library. If you use an earlier version of the compiler, you will receive an error when attempting to compile.

History

  • 2-Sep-2012: I added some links to grab the two most important files (the C# designer file and the C# code file). I also added a note about some strange behavior on different types of machines.
  • 4-Sep-2012: Consolidated source code (designer file + C# code file) into one file and uploaded the zip file to this article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

point64
Software Developer
United States United States
Software Development

Comments and Discussions

 
GeneralMy vote of 4 PinmemberChristian Amado2-Sep-12 5:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140415.2 | Last Updated 5 Sep 2012
Article Copyright 2012 by point64
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid