Arrange 2 List<string> to list box

巧了我就是萌 提交于 2019-12-12 02:54:15

问题


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()});
}

回答1:


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()));
    }



回答2:


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.


来源:https://stackoverflow.com/questions/10016745/arrange-2-liststring-to-list-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!