Start New Discussion within our Software Development Community

Hello,
I'm learning C# and i want to know how i can add a item in a ListBox like this, the user click in a button, then it creates a item in the ListBox and in the ListBox the user digits what he want in that field, when the user want to edit it he only double click in the item and he edits that value, but i don't know how to do this.

Best Regards,
Nathan Paulino Campos

Here is an example:

// example class to represent your item...
        class MyItem
        {
            public string Text { get; set; }

            // so listbox also knows how to display text for your item...
            public override string ToString() 
            {
                return Text;
            }
        }
        // handle double click event...
        // this.listBox1.DoubleClick += new System.EventHandler(this.listBox1_DoubleClick);
        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            // get selected item...
            object item = listBox1.SelectedItem;

            // view the text from your item. here I depend on override of ToString for your item...
            string s = item.ToString();

            // Here you pass it into your edit form...
            MyEditForm form2 = new MyEditForm(item); // you have to create the edit form...
            // when the form returns, "item" will contain the changes you made...
            form2.ShowDialog();

            // remove previous item...
            int index = listBox1.SelectedIndex;
            listBox1.Items.RemoveAt(index);
            // insert modified item...
            listBox1.Items.Insert(index, item);
        }
This article has been dead for over six months. Start a new discussion instead.