How to read column names of a multicolumn ListView control?

雨燕双飞 提交于 2019-12-11 02:12:55

问题


What is the best way to find the names of the columns of a ListView?

I converted a DataTable to a List using a procedure I found on this forum, but I cannot make it to put the Id column first, especially because not all of my DataTables have a column "Id".

I can search in collection listView.Columns.ToString() but the format I am seeing is:

"ColumnHeader: Text: Id"

which I have to parse to find the proper name "Id". This does not look like the spirit of C#.

I also tried: listView.SelectedItems[0].SubItems["Id"] but that does not compile.


Ok Here is the complete code. The exact problem is that the user selects a row in the listView with Courier Names and Ids, but it could also be Ids and Names, in that order. The fastest way to find the Id of the selected courier would be:

ListViewItem si = listCouriers.SelectedItems[0];
CourierId = si.SubItems["Id"].Text;

but that does not work. The hardcoded way would be this, but I cannot guarantee that some day the wrong column will be used:

ListViewItem si = listCouriers.SelectedItems[0];
CourierId = si.SubItems[1].Text;

Using @HuorSwords method leads to this not-so-simple solution, which works for me, but depends on the reasonable assumption that the order of columns in the ColumnHeaderCollection corresponds to the display on the form:

ListViewItem si = listCouriers.SelectedItems[0];
string CourierId = null;
int icol = 0;
foreach (ColumnHeader header in listCouriers.Columns)
{
    if (header.Text == "Id")
    {
        CourierId = si.SubItems[icol].Text;
        break;
    }
    icol++;
}

回答1:


As listView.Columns is of type ListView.ColumnHeaderCollection, then it contains ColumnHeader objects.

The ColumnHeader.Text contains the column title, so you can check for concrete column with:

foreach (ColumnHeader header in listView.Columns)
{
      if (header.Text == "Id")
      {
           // Do something...
      }
}

I don't know if is the best approach, but you don't need to parse the results to find "Id" value...

UPDATE

Also, have you tried to reference it with the String indexer? > listView.Columns["Id"]




回答2:


use this code:

private ColumnHeader GetColumn(string Text)
{
    for (int i = 0; i < listView1.Columns.Count; i++)
        for (int j = 0; j < listView1.Items.Count; j++)
            if (listView1.Items[j].SubItems.Count - 1 >= i)
                if (listView1.Items[j].SubItems[i].Text == Text)
                    return listView1.Columns[i];
    return null;
}

just give item text to this code and get everything you want of a column.

Enjoy ;)



来源:https://stackoverflow.com/questions/14985240/how-to-read-column-names-of-a-multicolumn-listview-control

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