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

偶尔善良 提交于 2020-01-31 19:15:33

问题


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.


回答1:


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;



回答2:


You can use ListViewItem directly to create an item with subitems (-> "tabular") instead of just adding strings to your ListView:

listView1.Items.Add(new ListViewItem (new[]{"John dsfsfsdfs", "1", "100"}));
listView1.Items.Add(new ListViewItem (new[]{"Smith sdfsdfsdfs", "2", "120"}));
listView1.Items.Add(new ListViewItem (new[]{"Cait dsffffffffffffffffffffff", "3", "97"}));
listView1.Items.Add(new ListViewItem (new[]{"Irene", "4", "100"}));
listView1.Items.Add(new ListViewItem (new[]{"Ben", "5, "100"}));
listView1.Items.Add(new ListViewItem (new[]{"Deniel           jjhkh", "6", "88"}));



回答3:


can you create a DataTable and bind it as a source

foreach (DataRow row in data.Rows)
{
    ListViewItem item = new ListViewItem(row[0].ToString());
    for (int i = 1; i < data.Columns.Count; i++)
    {
        item.SubItems.Add(row[i].ToString());
    }
    listView_Services.Items.Add(item);
}


来源:https://stackoverflow.com/questions/43841962/how-to-add-list-items-to-a-listview-in-cwinform

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