user3015248
user3015248

Reputation: 89

Add text to a column in a listview in C#

I have a table with two columns, and a button that when I click add text to two columns, the code I use for that is this:

    listView1.Items.Add("hi 1");
    listView1.Columns.Add("hi 2"); // ERROR

the issue is that the second column is not complete but if done right the first everything.

anyone can help me?

Upvotes: 2

Views: 8473

Answers (3)

keenthinker
keenthinker

Reputation: 7830

The ListView control can layout the items it contains differently. The layout that has also a Column header is the Details layout. It can be set using the View property of the ListView class.

Also you need first to add the columns and then add the items, so that the control knows how and where to put the items.

An example:

    var lv = new ListView();
    // set layout with column headers
    lv.View = View.Details;
    // add one column
    lv.Columns.Add("A");
    // add two items to column A
    lv.Items.Add("Item 1");
    lv.Items.Add("Item 2");

The output looks like this:

enter image description here

Bear in mind not to add the columns every time the button is clicked, but only once.

If you have more than one column, then every column after the first one, should be added as a SubItem of currently added ListViewItem item:

    // add two column
    lv.Columns.Add("A");
    lv.Columns.Add("B");
    // add one item to column A and B
    var lvi = lv.Items.Add("Item 1");
    lvi.SubItems.Add("SubItem 1");
    // add once again one row to column A and B
    lvi = lv.Items.Add("Item 2");
    lvi.SubItems.Add("SubItem 2");

The form looks like this:

enter image description here

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

You should add ListViewItem with array of subitems with item for each column in your ListView. If you have two columns:

listView1.Items.Add(new ListViewItem(new[] { "hi", "2" }));

Upvotes: 2

Jegadeesh
Jegadeesh

Reputation: 335

MyList.ForEach(name => listView1.Columns.Add(name));

Try this or

        ColumnHeader header = new ColumnHeader();
        header.Text = "gkgag";
        header.Width = 100;
        header.TextAlign = HorizontalAlignment.Center;
        listView1.Columns.Add(header);

Upvotes: 0

Related Questions