Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read column names of a multicolumn ListView control?

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++;
}
like image 898
Roland Avatar asked Oct 26 '25 09:10

Roland


1 Answers

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"]

like image 112
HuorSwords Avatar answered Oct 29 '25 00:10

HuorSwords



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!