Putting two-dimensional array in listbox

2019-04-17 05:46发布

问题:

So I have this array

string[,] cars = new String[2, 2] { 
                { "VW Golf GTI", "30000" }, 
                { "Porsche GT3", "300000" }, 
                { "Porsche Cayenne", "80000" }, 
                { "BMW M6", "90000" } 
            };

And want to put everything in a listbox, and I thought this would work, but it doesn't :/

lstBoxMarket.Items.AddRange(cars);

Now how do I put everything in the listbox in the format

Car - Price ?

回答1:

Try this:

string[,] cars = new string[4, 2] {
    { "VW Golf GTI", "30000" },
    { "Porsche GT3", "300000" },
    { "Porsche Cayenne", "80000" },
    { "BMW M6", "90000" }
};

for (int i = 0; i < cars.GetLength(0); i++)
{
    lstBoxMarket.Items.Add(cars[i, 0] + " - " + cars[i, 1]);
}

Your version of cars will not currently compile as you are specifying constants for the array initializers (2 rows by 2 columns) but your data has 4 rows.



回答2:

The better approach would be to Bind the ItemsSource to an ObservableCollection of a new class the data model Car type

Your view

.xaml

<StackPanel>
        <ListBox ItemsSource="{Binding DataCollection}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" />
                    <TextBlock Text=" - "/>
                    <TextBlock Text="{Binding Id}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
        </ListBox>
</StackPanel>

Your model Car.cs

public class Car
{
    public string Name { get; set; }
    public int Id { get; set; }
}

Your view model will have a Collection that will be bound to ItemsSource

CarViewModel.cs

public ObservableCollection<Car> DataCollection { get; set; }

DataCollection = new ObservableCollection<Car> 
{ 
    new Car { Name = "VW Golf GTI", Id = 30000 }, 
    new Car { Name = "Porsche GT3", Id = 30000 }, 
    new Car { Name = "Porsche Cayenne", Id = 80000 }, 
    new Car { Name = "BMW M6", Id = 90000 }
};


回答3:

USE DataSource property to load data of multidimensional array.

listBox1.MultiColumn = true;
    listBox1.DataSource = cars;