sledgehammer sledgehammer - 1 month ago 11x
C# Question

Accessing ProgressBar in ListView

I have the following code that I am trying to figure out but I am completely stumped. I am adding the progressbar into the listview, but I really don't know how to access each progressbar to update the progress values.

public ProgressBar LvAddProgB(ListView LV, int LVII, int LVColI, string lvName)
Rectangle SizeR = default(Rectangle);
ProgressBar ProgBar = new ProgressBar();

SizeR = LV.Items[LVII].Bounds;
SizeR.Width = LV.Columns[LVColI].Width;
if (LVColI > 0)
SizeR.X = SizeR.X + LV.Columns[LVColI - 1].Width;
ProgBar.Parent = LV;
ProgBar.Name = lvName;
ProgBar.SetBounds(SizeR.X, SizeR.Y, SizeR.Width, SizeR.Height);
ProgBar.Visible = true;
ProgBar.Maximum = 1000;
ProgBar.Step = 1;

return ProgBar;

private void button1_Click(object sender, EventArgs e)
for (int x = 0; x < 3; ++x)
ListViewItem item = new ListViewItem();
item.Text = "d.Name";
item.SubItems.Add(" ");
LvAddProgB(listView1, x, 1, "Lview" + x.ToString());


If you use a key of some sort, you can fish it back out of the Controls collection to update. Since each is displayed as if it was part of the ListView, it seems like there is some sort of linkage between the two. A key will also provide a way to link the item and related ProgressBar.

Assuming your ListView is Details view, just add a subitem at the end, without a related ColumnHeader. The data will not show, but will still be related to the Item. Use the same text as the ProgressBar name and it is easy to find.

My ListView has 3 columns: {Item, Name, Completion}, but the code will add a 4th subitem to store the key:

private void AddLVItem(string key, string name, int value)
    ListViewItem lvi = new ListViewItem();
    ProgressBar pb = new ProgressBar();

    lvi.SubItems[0].Text = name;
    lvi.SubItems.Add(key);            // LV has 3 cols; this wont show

    Rectangle r = lvi.SubItems[2].Bounds;
    pb.SetBounds(r.X, r.Y, r.Width, r.Height);
    pb.Minimum = 1;
    pb.Maximum = 10;
    pb.Value = value;
    pb.Name = key;                   // use the key as the name

Then, a method to update the Value and Progress bar for a given key:

private void UpdateItemValue(string key, int value)
    ListViewItem lvi;
    ProgressBar pb;

    // find the LVI based on the "key" in 
    lvi = lv.Items.Cast<ListViewItem>().FirstOrDefault(q => q.SubItems[3].Text == key);
    if (lvi != null)
        lvi.SubItems[1].Text = value.ToString();

    pb = lv.Controls.OfType<ProgressBar>().FirstOrDefault(q => q.Name == key);
    if (pb != null)
        pb.Value = value;


// add some data
AddLVItem("A", "Ziggy", 1);
AddLVItem("B", "Zacky", 1);
AddLVItem("C", "Zoey", 1);
AddLVItem("D", "Zeke", 1);

// update the displayed value and progressbar using the key:
UpdateItemValue("A", 6);
UpdateItemValue("B", 5);
UpdateItemValue("C", 8);
UpdateItemValue("D", 2);

enter image description here