[英]How to count the SubItems in a ListView?
這是你的解決方案
//iterate through all rows
for (int i = 0; i < listView1.Items.Count; i++)
{
//make sure that 5 subitems are present
int missingSubitemsCount = 5 - listView1.Items[i].SubItems.Count;
for (int j = 0; j < missingSubitemsCount; j++)
listView1.Items[i].SubItems.Add(new ListViewItem.ListViewSubItem());
int count = 0;
//test columns 1-3
for (int j = 1; j < listView1.Items[i].SubItems.Count - 1; j++)
{
//check if empty
if (String.IsNullOrEmpty(listView1.Items[i].SubItems[j].Text) == false)
count++;
}
//update last column
listView1.Items[i].SubItems[4].Text = count.ToString();
}
但是,我認為使用 DataGridView 和數據綁定會更好。 當項目變得更大時,直接在控件上操作可能會導致問題。 將數據與視圖分開更好
這是我將如何使用 DataGridView
class MyItem
{
public string Name { get; set; }
public string Property1 { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
public int Total { get; set; }
}
private void button2_Click(object sender, EventArgs e)
{
var items = new List<MyItem>();
items.Add(new MyItem
{
Name = "Books",
Property1 = "A",
Property2 = "B",
Property3 = "C"
});
items.Add(new MyItem
{
Name = "Pencils",
Property1 = "A",
Property2 = "B",
});
items.Add(new MyItem
{
Name = "Tapes",
Property1 = "A",
});
//iterate through all items
foreach (var item in items)
{
//get list of MyItem properties starting with "Property"
foreach (var property in typeof(MyItem).GetProperties().Where(u => u.Name.StartsWith("Property")))
{
//test if null or empty, increment Total if not
if (property.GetValue(item) != null && String.IsNullOrEmpty(property.GetValue(item).ToString()) == false)
item.Total++;
}
//Alternative: Same calculation in one line
item.Total = typeof(MyItem).GetProperties().Count(u => u.Name.StartsWith("Property") && u.GetValue(item) != null && String.IsNullOrEmpty(u.GetValue(item).ToString()) == false);
}
//bind items to DataGridView
dataGridView1.DataSource = items;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.