Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How we can refresh items text in ListBox without reinserting it?

I have the class TestClass that has ToString overriden (it returns Name field). I have instances of TestClass added into ListBox and at certain point I need to change Name of one of this instances, how then I can refresh it's text in ListBox?

using System;
using System.Windows.Forms;

namespace TestListBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            listBox1.Items.Add(new TestClass("asd"));
            listBox1.Items.Add(new TestClass("dsa"));
            listBox1.Items.Add(new TestClass("wqe"));
            listBox1.Items.Add(new TestClass("ewq"));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ((TestClass)listBox1.Items[0]).Name = "123";
            listBox1.Refresh(); // doesn't help
            listBox1.Update(); // same of course
        }
    }

    public class TestClass
    {
        public string Name;

        public TestClass(string name)
        {
            this.Name = name;
        }

        public override string ToString()
        {
            return this.Name;
        }
    }
}
like image 322
Kosmo零 Avatar asked Nov 28 '22 06:11

Kosmo零


1 Answers

try

listBox1.Items[0] = listBox1.Items[0];
like image 132
Martin Staufcik Avatar answered Dec 10 '22 03:12

Martin Staufcik