Someone
Someone

Reputation: 379

Listbox with multiple columns of the same contents

Is it possible to make multiple columns in a ListBox control using WinForms? The columns should have one DataSource. Example:

1    5
2    6
3    7
4    8

I want to assign, for example, a list of int to a ListBox, but I want to have multiple columns. I mean, I want to have one column that wraps. I hope I explained it fine...

Upvotes: 0

Views: 1010

Answers (2)

Hans Passant
Hans Passant

Reputation: 941645

Sure, it is a built-in feature that you can simply enable with the designer. Set the MultiColumns property to True and the ColumWidth property to a value larger than 0. That's all, the horizontal scrollbar automatically appears when the content doesn't fit the box.

Upvotes: 1

roemel
roemel

Reputation: 3297

I'd suggest using a DataGridView instead of a ListBox to display more than one column. I'll give you an example.

Using a DataTable as DataSource:

DataTable dt = new DataTable();
dt.Columns.Add("Column1");
dt.Columns.Add("Column2");

dt.Rows.Add("1", "5");
dt.Rows.Add("2", "6");
dt.Rows.Add("3", "7");
dt.Rows.Add("4", "8");

dataGridView1.DataSource = dt;

Using a generic list as DataSource:

List<YourClass> list = new List<YourClass>();

YourClass yc = new YourClass();
yc.Column1 = "1";
yc.Column2 = "5";

list.Add(yc);
dataGridView1.DataSource = list;

public class YourClass
{
    public string Column1 { get; set; }
    public string Column2 { get; set; }
}

Upvotes: 2

Related Questions