I've got some troubles with ListBox. I want to allow user edit selected item in ListBox, when he double click it in his application, but I wasn't able to find how to do this. Please, can someone help me with it?

Recommended Answers

All 2 Replies

ListBox class does not support editing items in runtime (at least I do not know anything about it ;-P). So you have to handle yourself... As you want to give the user opportunity to change data after double clicking use DoubleClick event of the ListBox class and add in there the code. Depending on how you want a user to provide data to the app it will look differently.
Probably the simplest way to achieve what you want is to add TextBox control to the form. Then the DoubleClick event can look somehow like this:

private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            int selectedElement = listBox1.SelectedIndex;
            listBox1.Items[selectedElement] = editText.Text;
        }

To be more sophisticated you can hide the textbox and show it only when it will be needed.
Sample code:

public partial class Form1 : Form
    {
        private TextBox editText;
        private int selectedElement;

        public Form1()
        {
            InitializeComponent();
        }

        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            selectedElement = listBox1.SelectedIndex;
            editText.Show();
            editText.Focus();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            editText = new TextBox();
            editText.Location = new Point(10, 0);
            editText.Size = new Size(100, 20);
            editText.Text = "";
            editText.Hide();
            listBox1.Controls.Add(this.editText);
            editText.LostFocus += new System.EventHandler(this.FocusLost);
        }

        private void FocusLost(object sender, System.EventArgs e)
        {
            listBox1.Items[selectedElement] = editText.Text;
            editText.Text = "";
            editText.Hide();
        }
    }

Having that you have to just work on the specific location of the textbox when it shows and other less important details...

Szpilona, thanks a lot!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.