Newuser
Newuser

Reputation: 399

Clear contents of specific listview columns?

This is how I currently add info to my listview:

private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
    int totItems = Seq3.Count - 1;
    if (PercentPopTolerance1.Count - 1 > totItems) totItems = PercentPopTolerance1.Count - 1;

    for (int i = 0; i <= totItems; i++)
    {
        ListViewItem lvi = new ListViewItem();
        string item1 = "";
        string item2 = "";

        if (Seq3.Count - 1 >= i) item1 = Seq3[i].ToString();
        if (PercentPopTolerance1.Count - 1 >= i) item2 = PercentPopTolerance1[i].ToString();

        lvi.SubItems.Add(item1);
        lvi.SubItems.Add(item2);

        listView2.Items.Add(lvi);
    }
}

View of empty listview:

enter image description here

Now how would I clear the contents of any particular column? Say I want to add to column YYMM but before I do this, I want to clear that particular column. How would this be done?

Upvotes: 0

Views: 1234

Answers (2)

King King
King King

Reputation: 63317

You should specify a column by its name (a column corresponds to a subitem in a ListViewItem), note that this Name is not ColumnHeader.Name, I mean the corresponding ListViewSubItem.Name:

public void ClearColumn(string colName){
  foreach(ListViewItem item in listView1.Items){
    var cell = item.SubItems[colName];
    if(cell != null) cell.Text = "";
  }
}

The following code will work for ColumnHeader.Name passed in instead of ListViewSubItem.Name as the code above does:

public void ClearColumn(string columnHeaderName){
  int i = listView1.Columns.IndexOfKey(columnHeaderName);
  if(i == -1) return;
  foreach(ListViewItem item in listView1.Items){
    item.SubItems[i].Text = "";
  }
}

You can try the following code to make it work for Text instead of Name:

public void ClearColumn(string colText){
  if(listView1.Items.Count == 0) return;
  var col =  listView1.Columns.Cast<ColumnHeader>()
                      .Select((x,i)=>new{x,i})
                      .FirstOrDefault(a=>a.x.Text == colText);
  if(col == null) return;
  foreach(ListViewItem item in listView1.Items){
    item.SubItems[col.i].Text = "";
  }
}

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You can clear column values like this

        var items = listView1.Items;

        foreach (ListViewItem item in items)
        {
            a.SubItems["YYWW"].Text = "";
        }

Upvotes: 1

Related Questions