Creating A Console ListBox In C#

Introduction

C# developers who are interested in console programming are often frustrated by the lack of user interface features that the console has compared to Windows Forms and WPF applications.

Well, despite the limitations of its text-based interface, you can, with a bit of effort, produce console versions of some of the simpler Windows 'controls', and in this article, I'd like to show you how to produce a list box.

To do this, we need to draw a box on the console, and fortunately, the Unicode character set (as did MS-DOS code pages before it) supports a number of box drawing characters (see http://en.wikipedia.org/wiki/Box-drawing_characters).

Example. Here's the source code for producing a basic listbox containing the names of the 12 months of the year.

using System;
class ConsoleListBox
{
    static void Main()
    {
        Console.TreatControlCAsInput = false;
        Console.CancelKeyPress += new ConsoleCancelEventHandler(BreakHandler);
        Console.Clear();
        Console.CursorVisible = false;
        string[] months = {
            "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
        };
        WriteColorString("Choose Level using down and up arrow keys and press enter", 12, 20, ConsoleColor.Black, ConsoleColor.White);

        int choice = ChooseListBoxItem(months, 34, 3, ConsoleColor.Blue, ConsoleColor.White);
        // do something with choice
        WriteColorString("You chose " + months[choice - 1] + ". Press any key to exit", 21, 22, ConsoleColor.Black, ConsoleColor.White);
        Console.ReadKey();
        CleanUp();
    }
    public static int ChooseListBoxItem(string[] items, int ucol, int urow, ConsoleColor back, ConsoleColor fore)
    {
        int numItems = items.Length;
        int maxLength = items[0].Length;
        for (int i = 1; i < numItems; i++)
        {
            if (items[i].Length > maxLength)
            {
                maxLength = items[i].Length;
            }
        }
       

Output

When you build and run this program, the console should look like this.

console list box


Similar Articles