1

I have a C# .NET WinForm. In the form, I allow a user to add an item to a ListView by double-clicking in the ListView. This adds a TextBox control to the ListView and places the key cursor in the TextBox so a user can type.

I detect that a user is done with an item in a couple of ways (e.g. pressing Enter, Esc, Tab...), but also when they Leave (TextBox.Leave) the TextBox.

The problem is this set of steps:

  1. User triggers TextBox.Leave by mousing down outside of the TextBox.
  2. I add the new item to the ListView.
  3. I select the the new item in the ListView.
  4. Mouse up occurs and the new item that I just selected, loses focus and is unselected.

What I would like is for TextBox.Leave to be triggered by MouseUp, not MouseDown. How can I accomplish this?

Edit: Cody suggests using the ListView.LabelEdit property. Here are my results trying that:

listView_DoubleClick(...) {
  listView.LabelEdit = true;
  if(double clicked on existing listViewItem) {
     listViewItem.BeginEdit();  //this works as expected
  } else {
     var newItem = listView.Items.Add("");
     newItem.BeginEdit();       //this doesn't work, see below  
  }
}

The call to newItem.BeginEdit() only works when the user double clicks where the new item will show up. If they double click on any other blank area in the listview the new item is added, but it does not enter edit mode. What's going on here?

Chad
  • 3,159
  • 4
  • 33
  • 43
  • That's a very, *very* strange way to add a row to a `ListView` control. Why should you need a separate `TextBox` control? Have you tried setting the [`LabelEdit` property](http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.labeledit.aspx) to True? Alternatively, I would consider using a `DataGridView` control, if you need to allow the user to add items at runtime. – Cody Gray - on strike Mar 06 '11 at 09:16
  • @Cody - I'm trying the LabelEdit now, but seeing strange behavior. See my update. – Chad Mar 06 '11 at 10:06

1 Answers1

0

Pressing the mouse down on another control is causing that other control to request the focus and so the focus moving causes the TextBox.Leave event to occur. Preventing ever other possible control from requesting the focus is not a very viable option. But luckly you only need to prevent the ListView from using the MouseDown to shift focus. So you need to override the WndProc of your ListView and when the MouseDown windows message occurs and you are currently showing a TextBox you eat the message. In order words you do not allow the base class to process it.

Phil Wright
  • 22,580
  • 14
  • 83
  • 137