Search code examples
c#winformslistview

How to add list items to a ListView in C#winform?


I have a list of objects. I want to add these items to a ListView. I'm trying to add each list item row wise but format is very bad, it should be in proper table type format.

        List<string> lst = new List<string>();
        lst.Add("John dsfsfsdfs " + "1" + 100);
        lst.Add("Smith sdfsdfsdfs" + "2" + 120);
        lst.Add("Cait dsffffffffffffffffffffff" + "3" +  97);
        lst.Add("Irene" + "4" + 100);
        lst.Add("Ben"     + "5" + 100);
        lst.Add("Deniel           jjhkh " +  "6" + 88);

        foreach(string pl in lst)
        {
            listView1.Items.Add(pl);

        }

Items are not visible and it should be in proper format.

Table Format


Solution

  • To make it multicolumn:

    1) set the ListView into Details mode:

        listView1.View = View.Details;
    

    2)set up your three columns:

        listView1.Columns.Add("Column1Name");
        listView1.Columns.Add("Column2Name");
        listView1.Columns.Add("Column3Name");
    

    3) add your items:

        listView1.Items.Add(new ListViewItem(new string[]{"John dsfsfsdfs ", "1" , "100"}));
    

    4) To make it more viewable try:

    listView1.GridLines = true;
    

    5) To hide columns headers:

     listView1.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;