Arrange 2 List<string> to list box

i have 2 List that i want to put into my Listbox the first List contain names and the second contain numbers my problem is that some of the names long so the numbers cannot a display in the same line how can i put in in appropriate way ?

listBox.Items.Add("Name" + "\t\t\t" + "Number");
for (int i = 0; i < lists.Count; i++)
{
    listBox.Items.Add(lists._namesList[i] + "\t\t\t" + lists._numbersList[i]);
}

Update here is what I tried with a ListView

listViewProtocols.View = View.Details;
listViewProtocols.Columns.Add("Name");
listViewProtocols.Columns.Add("Number");

for (int i = 0; i < lists._protocolsList.Count; i++)
{
    listViewProtocols.Items.Add(new ListViewItem{ lists._nameList[i], lists._numbersList[i].ToString()});
}

Answers


Consider using a ListView component, with Details style. As @Yuck mentioned in the comments it will give you the effect you need.

It is a bit akward to populate from 2 separate lists but it is doable with the code below:

listView1.View=View.Details;
listView1.Columns.Add("Name");
listView1.Columns.Add("Number");

string[] names= { "Abraham", "Buster", "Charlie" };
int[] numbers= { 1018001, 1027400, 1028405 };

for(int i=0; i<names.Length; i++)
{
    listView1.Items.Add(
        new ListViewItem(new string[] {
        names[i], numbers[i].ToString() }));                
}

I would strongly recommend doing an array of structures instead of separate lists like this:

public struct Record
{
    public string name;
    public int number;

    public string[] ToStringArray()
    {
        return new string[] {
            name,
            number.ToString() };
    }
}

and used like this:

    listView1.View=View.Details;
    listView1.Columns.Add("Name");
    listView1.Columns.Add("Number");

    Record[] list=new Record[] {
        new Record() { name="Abraham", number=1018001 },
        new Record() { name="Buster", number=1027400 },
        new Record() { name="Charlie", number=1028405 }
    };

    for(int i=0; i<list.Length; i++)
    {
        listView1.Items.Add(
            new ListViewItem(list[i].ToStringArray()));
    }

There are couple of options I can think of:

  1. Make the listbox wider so that it can accomodate longer text or add a horizontal scrollbar to it.
  2. Constrain the max length of names to, let's say, 20 chars and replace extra characters with ....
  3. Probably the best solution is to use grid instead of listbox - you need to display two columns of data, which is exactly the grid is for.

Need Your Help

Automatic e-mail extraction in Java

java text-extraction email-address

How can I scan for potential e-mail addresses in a text file using Java?

How to remove all lines in a file, then rewrite the file in Compact Framework 3.5 c#

c# .net compact-framework windows-ce streamwriter

In the .net framework using a Windows Forms app I can purge a file, then write the data that I want back to into that file.