查找 ListView 列名称的最佳方法是什么?
我使用在该论坛上找到的过程将 DataTable 转换为列表,但我无法将 Id 列放在第一位,特别是因为并非所有 DataTable 都有“Id”列。
我可以在集合 listView.Columns.ToString() 中搜索,但我看到的格式是:
“列标题:文本:ID”
我必须解析它才能找到正确的名称“Id”。
这看起来不太像C#的精神。
我也尝试过:listView.SelectedItems[0].SubItems["Id"]
但这不能编译。
好的,这是完整的代码。
确切的问题是,用户在 listView 中选择带有 Courier Names 和 Ids 的行,但也可能按此顺序选择 Ids 和 Names。查找所选快递员 ID 的最快方法是:
ListViewItem si = listCouriers.SelectedItems[0];
CourierId = si.SubItems["Id"].Text;
但这不起作用。硬编码的方式是这样的,但我不能保证有一天会使用错误的列:
ListViewItem si = listCouriers.SelectedItems[0];
CourierId = si.SubItems[1].Text;
使用 @HuorSwords 方法会导致这个不那么简单的解决方案,它对我有用,但取决于合理的假设,即列中的顺序ColumnHeaderCollection
对应表单上的显示:
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++;
}