0

enter image description here

I would like to double click on an item in the list box and have that item show up in the textBox titled File name (please refer to the picture)

private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
  listBox1.Items.Add(textBox2.Text);
}

this code does not work, what am I doing wrong

Marcel N.
  • 13,726
  • 5
  • 47
  • 72
Kiwilad
  • 85
  • 1
  • 1
  • 12

2 Answers2

2

You're doing it other way around. You try to add the text from textbox to listbox.

private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    if(listBox1.SelectedItem != null)
    {
        textBox2.Text = listBox1.SelectedItem.ToString();
    }
}

To get more reliable results when clicking no item in listbox, you can use this answer. Thanks to @Marcel N.

Community
  • 1
  • 1
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • Doesn't always work. If you have an item already selected and double-click the blank are then you get a false hit. The answer in [this question](http://stackoverflow.com/questions/4454423/c-sharp-listbox-item-double-click-event) is more reliable in this regard. – Marcel N. Aug 10 '14 at 09:06
  • @MarcelN. I guess in that scenario `SelectedItem` will be set to null, so it won't result in false hit. – Sriram Sakthivel Aug 10 '14 at 09:09
  • @SriramSakthivel: It will not :). You can test it, it occurs consistently. – Marcel N. Aug 10 '14 at 09:09
  • @MarcelN. Yes you're right.. – Sriram Sakthivel Aug 10 '14 at 09:16
  • @SriramSakthivel: I guess it's not a big downside, especially for OP and the item does stay selected when double-clicking so it is not confusing. Something worth noting nonetheless. – Marcel N. Aug 10 '14 at 09:19
0

Your code does not add any text to your textbox from your listbox. For your purpose you need to use this code:

private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
  textBox2.Text = listBox1.SelectedItem.ToString();
}

You don't need to use any if, because when you have some items in your listbox, you can just click or double click on them. When you don't have any items, you won't have any things to click, so null could never be returned. I tested it, and you can try too.

Matin Lotfaliee
  • 1,745
  • 2
  • 21
  • 43