Wednesday, July 23, 2014

Making columns in a listbox in C#

Amended: There is a MultiColumn property I forgot to mention. It didn't work for me with the particular problem I had. Maybe that was my lack of skill. Maybe it was the problem. In any case, try MultiColumn and try my workaround. One of them should do the trick.

This post probably has a very limited audience made up of other students who, like me, are being forced to use Windows Forms and have not yet used WPF. Having not used WPF yet, I don't know if this helpful hint will help outside Windows Forms.

Here was my problem: I had a lab assignment in which I was required to make a GUI in Windows Forms. Random integers were to be created with a button click and the values displayed in a listbox with two columns. I suddenly realized I didn't know how to make columns in a listbox.  Very old versions of Visual Studio had a columns property but since I was using VS 2013, that didn't help. I also read somewhere that listview could be used but it was described as "quirky." I didn't have time for quirky.

So here's how to do it:

        Step 1: listBox1.Items.Add("Index     Values");
        Step 2: Make a for loop
        Step 3:  Inside the for loop, add the output underneath the column headings
                    from Step 1.
                    listBox1.Items.Add(string.Format("{0}           {1}", i, intArray[i]));

That's it. Pretend you're in a Console app but use listbox instead and you've got columns.

No comments:

Post a Comment