[英]C# Listview duplicating group name
if (comboBox1.Text == "1")
{
int group1 = 0;
group1 = listView1.Groups.Add(new ListViewGroup("Group 1"));
listView1.ShowGroups = true;
listView1.View = View.Details;
string[] row = { textBox1.Text, textBox2.Text, textBox3.Text };
ListViewItem lvi1 = new ListViewItem(row);
lvi1.Group = listView1.Groups[group1];
listView1.Items.Add(lvi1);
}
如果選擇組1並已創建,則應將數據添加到該組中,而不創建重復項。
有兩種方法:
檢查是否已經有一個組。
刪除舊的組,然后每次重新創建。
我絕對是方法1的粉絲,因為它只需要簡單檢查即可。 方法2將需要做更多的工作,如果您想使用ListView
的項目,您可能會生氣,因為它們可能不再存在(一旦將它們刪除並重新創建)。
不確定我是否正確地回答了您的問題,詳細說明您的問題可能會有所幫助。
if (comboBox1.Text == "1")
{
var groupLabel = "Group 1";
var group = listView1.Groups[groupLabel];
if (group == null)
{ // group did not exist - let's create it and add it to the view
group = new ListViewGroup(groupLabel);
listView1.Groups.Add(group);
}
listView1.ShowGroups = true;
listView1.View = View.Details;
string[] row = { textBox1.Text, textBox2.Text, textBox3.Text };
ListViewItem lvi1 = new ListViewItem(row) {Group = group};
listView1.Items.Add(lvi1);
}
如果在GroupCollection上使用字符串索引器,並且不存在具有該字符串(即名稱)的組,則將得到null。 這就是創建它並將其插入集合的線索。
您總是可以將所有這些封裝在擴展類中
public static class ListViewExt
{
public ListViewGroup GetGroup(this ListView view, string groupLabel)
{
var group = view.Groups[groupLabel];
if (group == null)
{ // group did not exist - let's create it and add it to the view
group = new ListViewGroup(groupLabel);
view.Groups.Add(group);
}
return group;
}
}
然后在您的代碼中調用它:
if (comboBox1.Text == "1")
{
listView1.ShowGroups = true;
listView1.View = View.Details;
string[] row = { textBox1.Text, textBox2.Text, textBox3.Text };
ListViewItem lvi1 = new ListViewItem(row) {Group = listView1.GetGroup("Group 1")};
listView1.Items.Add(lvi1);
}
對我來說,訪問listview.group[name]
的解決方案始終返回null。
因此,我使用了一些linq來實現相同的目的:
ListViewGroup lvg = this.listView_History.Groups.Cast<ListViewGroup>()
.Where(x => x.Header == "MyString").FirstOrDefault();
if (lvg == null)
{
lvg = new ListViewGroup("MyString");
listView_History.Groups.Add(lvg)
}
ListViewItem LVI = new ListViewItem();
LVI.Group = lvg;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.