Quite a simple question but I think its going to prove much harder than it sounds
I'd like to keep the selection of a listview item there when the focus leaves the list view, at the moment I've set the hideselection property to false and that's fine.. it does cause a VERY light gray selection to stay after the list view loses focus, so my question is, how can I properly show that that item is still selected so that the user will recognize that, something like changing the rows text colour or background colour? or just keeping it highlighted as when first selected the whole row turns blue?
I've had a look through intelisense and can't seem to find anything for a row or item or selected item's individual colour property?
It must exist though because selected items have their own background colour, where would I be able to change that?
Oh and the list view does need to stay in details view, which means I can't use the only method that I've been able to find whilst googling
thanks
Here's a solution for a ListView that does not allow multiple selections and
does not have images (e.g. checkboxes).
Set event handlers for the ListView (in this example it's named listView1):
DrawItem
Leave (invoked when the ListView's focus is lost)
Declare a global int variable (i.e. a member of the Form that contains the ListView,
in this example it's named gListView1LostFocusItem) and assign it the value -1
int gListView1LostFocusItem = -1;
Implement the event handlers as follows:
private void listView1_Leave(object sender, EventArgs e)
{
// Set the global int variable (gListView1LostFocusItem) to
// the index of the selected item that just lost focus
gListView1LostFocusItem = listView1.FocusedItem.Index;
}
private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
// If this item is the selected item
if (e.Item.Selected)
{
// If the selected item just lost the focus
if (gListView1LostFocusItem == e.Item.Index)
{
// Set the colors to whatever you want (I would suggest
// something less intense than the colors used for the
// selected item when it has focus)
e.Item.ForeColor = Color.Black;
e.Item.BackColor = Color.LightBlue;
// Indicate that this action does not need to be performed
// again (until the next time the selected item loses focus)
gListView1LostFocusItem = -1;
}
else if (listView1.Focused) // If the selected item has focus
{
// Set the colors to the normal colors for a selected item
e.Item.ForeColor = SystemColors.HighlightText;
e.Item.BackColor = SystemColors.Highlight;
}
}
else
{
// Set the normal colors for items that are not selected
e.Item.ForeColor = listView1.ForeColor;
e.Item.BackColor = listView1.BackColor;
}
e.DrawBackground();
e.DrawText();
}
Note: This solution can result in some flicker. A fix for this involves subclassing the ListView control so you
can change the protected property DoubleBuffered to true.
public class ListViewEx : ListView
{
public ListViewEx() : base()
{
this.DoubleBuffered = true;
}
}
I created a class library of the above class so that I could add it to the toolbox.
A possible solution might be this answer to an another question:
How to change listview selected row backcolor even when focus on another control?
Related
I have a databound combobox:
using(DataContext db = new DataContext())
{
var ds = db.Managers.Select(q=> new { q.ManagerName, q.ManagerID});
cmbbx_Managers.BindingContext = new BindingContext();
cmbbx_Managers.DataSource = ds;
cmbbx_Managers.DisplayMember = "ManagerName";
cmbbx_Managers.ValueMember = "ManagerID";
}
When the form loads neither item is selected, but when the user chooses an item it cannot be deselected. I tried to add cmbbx_Managers.items.Insert(0, "none"), but it does not solve the problem, because it is impossible to add a new item to the databound combobox.
How do I allow a user to deselect a combobox item?
To add an item to your databound ComboBox, you need to add your item to your list which is being bound to your ComboBox.
var managers = managerRepository.GetAll();
managers.Insert(0, new Manager() { ManagerID = 0, ManagerName = "(None)");
managersComboBox.DisplayMember = "ManagerName";
managersComboBox.ValueMember = "ManagerID";
managersComboBox.DataSource = managers;
So, to deselect, you now simply need to set the ComboBox.SelectedIndex = 0, or else, use the BindingSource.CurrencyManager.
Also, one needs to set the DataSource property in last line per this precision brought to us by #RamonAroujo from his comment. I updated my answer accordingly.
The way you "deselect" an item in a drop-down ComboBox is by selecting a different item.
There is no "deselect" option for a ComboBox—something always has to be selected. If you want to simulate the behavior where nothing is selected, you'll need to add a <none> item (or equivalent) to the ComboBox. The user can then select this option when they want to "deselect".
It is poor design that, by default, a ComboBox appears without any item selected, since the user can never recreate that state. You should never allow this to happen. In the control's (or parent form's) initializer, always set the ComboBox to a default value.
If you really need a widget that allows clearing the current selection, then you should use a ListView or ListBox control instead.
To deselect an item suppose the user presses the Esc key, you could subscribe to the comboxBox KeyDown event and set selected index to none.
private void cmbbx_Managers_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape && !this.cmbbx_Managers.DroppedDown)
{
this.cmbbx_Managers.SelectedIndex = -1;
}
}
i have 2 listBoxes in a window, one next to the other, with buttons to copy items from one listBox to the other.
when an item from the first listBox is selected the copy button gets enabled, and remove button gets disabled. when i choose an item for the second listBox the copy button gets disabled, and remove button gets enabled.
when you select an item in one of the listBoxes the buttons change with no problem, after the listBox lost focus and you choose the same item that was selected the buttons dont change back.
i understand the problem is that the event of selected item changed will not fire, beacuse the selected item did not change.
setting the selected item to null when the listBox loses focus was not usefull beacuse i need the selcted item. i need to find a way to reselect the selected item when the listBox gains focus, or just fire the even of selected item changed. any suggestions?
You can try the ListBox.LostFocus Event and set the SelectedItem Property to null.
private void ListBox_LostFocus(object sender, RoutedEventArgs e)
{
((ListBox)sender).SelectedItem = null;
}
Use the ListBox.GotFocus event check if there is a SelectedItem, store the index, remove the SelectedItem and use the stored index to reset the SelectedItem. Something like this
private void ListBox_GotFocus(object sender, RoutedEventArgs e)
{
ListBox lb = (ListBox)sender;
if(lb.SelectedItem != null )
{
int index = lb.SelectedIndex;
lb.SelectedItem = null;
lb.SelectedIndex = index;
}
}
I have a program which uses a barcode scanner as input device so that means I need to keep the focus on a text box.
The program has a listview control and I select one of the items programatically when a certain barcode is scanned. I set the background color of the row by:
listviewitem.BackColor = Color.LightSteelBlue;
Things I have tried:
listview.HideSelection set to false
call listview.Focus() after setting the color
listviewitem.Focused set to true
call listview.Invalidate
call listview.Update()
call listview.Refresh()
different combinations of the above
I've also did combinations above stuff in a timer so that they are called on a different thread but still no success.
Any ideas?
More info:
The key here is the control focus. The listview control does not have the focus when I select one of the items.
I select one item by doing:
listView1.Items[index].Selected = true;
the Focus is always in the textbox.
the computer does not have keyboard or mouse, only a barcode reader.
I have this code to keep the focus on the textbox:
private void txtBarcode_Leave(object sender, EventArgs e)
{
this.txtBarcode.Focus();
}
You need to have a textbox add that code to simulate my problem.
What you describe works exactly as expected, assuming that you've set the HideSelection property of the ListView control to False. Here's a screenshot for demonstration purposes. I created a blank project, added a ListView control and a TextBox control to a form, added some sample items to the ListView, set its view to "Details" (although this works in any view), and set HideSelection to false. I handled the TextBox.Leave event just as you showed in the question, and added some simple logic to select the corresponding ListViewItem whenever its name was entered into the TextBox. Notice that "Test Item Six" is selected in the ListView:
Now, as I suspected initially, you're going to mess things up if you go monkeying around with setting the BackColor property yourself. I'm not sure why you would ever want to do this, as the control already uses the default selection colors to indicate selected items by default. If you want to use different colors, you should change your Windows theme, rather than trying to write code to do it.
In fact, if I add the line item.BackColor = Color.LightSteelBlue in addition to my existing code to select the ListViewItem corresponding to the name typed into the TextBox, I get exactly the same thing as shown above. The background color of the item doesn't change until you set focus to the control. That's the expected behavior, as selected items look different when they have the focus than they do when their parent control is unfocused. Selected items on focused controls are painted with the system highlight color; selected items on unfocused controls are painted with the system 3D color. Otherwise, it would be impossible to tell whether or not the ListView control had the focus. Moreover, any custom BackColor property is completely ignored by the operating system when the ListView control has the focus. The background gets painted in the default system highlight color.
Explicitly setting the focus to the ListView control, of course, causes the custom background color to be applied to the ListViewItem, and things render with a color that very much contrasts with the color scheme that I've selected on my computer (remember, not everyone uses the defaults). The problem, though, becomes immediately obvious: you can't set the focus to the ListView control because of the code you've written in the TextBox.Leave event handler method!
I can tell you right now that setting the focus in a focus-changing event is the wrong thing to do. It's a hard rule in Windows you're not allowed to do things like that, and the documentation even warns you explicitly not to do it. Presumably, your answer will be something along the lines of "I have to", but that's no excuse. If everything were working as expected, you wouldn't be asking this question in the first place.
So, what now? Your application's design is broken. I suggest fixing it. Don't try and monkey with setting the BackColor property yourself to indicate that an item is selected. It conflicts with the default way that Windows highlights selected items. Also, don't try and set the focus in a focus-changing event. Windows explicitly forbids this, and the documentation is clear that you're not supposed to do this. If the target computer doesn't have a mouse or keyboard, it's unclear how the user is going to set focus to anything else in the first place, unless you write code to do it, which you shouldn't be doing.
But I have surprisingly little faith that you'll want to fix your application. People who ignore warnings in the documentation tend to be the same people who don't listen to well-meaning advice on Q&A sites. So I'll throw you a bone and tell you how to get the effect you desire anyway. The key lies in not setting the ListViewItem's Selected property, which avoids the conflict between your custom BackColor and the system default highlight color. It also frees you from having to explicitly set the focus to the ListView control and back again (which, as we established above, isn't actually happening, given your Leave event handler method). Doing that produces the following result:
And here's the code—it's not very pretty, but this is just a proof of concept, not a sample of best practice:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listView1.View = View.Details;
listView1.HideSelection = false;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
foreach (ListViewItem item in listView1.Items)
{
if (item.Text == textBox1.Text)
{
item.BackColor = Color.LightSteelBlue;
return;
}
}
}
private void textBox1_Leave(object sender, EventArgs e)
{
this.textBox1.Focus();
}
}
A standard ListView does not let you set the background color of a selected row. The background (and foreground) colors of a selected row are always controlled by the theme of the OS.
You have to owner draw your ListView to get around this OR you can use ObjectListView. ObjectListView is an open source wrapper around .NET WinForms ListView, which makes it much easier to use, as well as easily allowing things that are very difficult in a normal ListView -- like changed the colors of selected rows.
this.objectListView1.UseCustomSelectionColors = true;
this.objectListView1.HighlightBackgroundColor = Color.Lime;
this.objectListView1.UnfocusedHighlightBackgroundColor = Color.Lime;
This shows the ObjectListView when it does not have focus.
Here's a solution for a ListView that does not allow multiple selections and
does not have images (e.g. checkboxes).
Set event handlers for the ListView (in this example it's named listView1):
DrawItem
Leave (invoked when the ListView's focus is lost)
Declare a global int variable (i.e. a member of the Form that contains the ListView,
in this example it's named gListView1LostFocusItem) and assign it the value -1
int gListView1LostFocusItem = -1;
Implement the event handlers as follows:
private void listView1_Leave(object sender, EventArgs e)
{
// Set the global int variable (gListView1LostFocusItem) to
// the index of the selected item that just lost focus
gListView1LostFocusItem = listView1.FocusedItem.Index;
}
private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
// If this item is the selected item
if (e.Item.Selected)
{
// If the selected item just lost the focus
if (gListView1LostFocusItem == e.Item.Index)
{
// Set the colors to whatever you want (I would suggest
// something less intense than the colors used for the
// selected item when it has focus)
e.Item.ForeColor = Color.Black;
e.Item.BackColor = Color.LightBlue;
// Indicate that this action does not need to be performed
// again (until the next time the selected item loses focus)
gListView1LostFocusItem = -1;
}
else if (listView1.Focused) // If the selected item has focus
{
// Set the colors to the normal colors for a selected item
e.Item.ForeColor = SystemColors.HighlightText;
e.Item.BackColor = SystemColors.Highlight;
}
}
else
{
// Set the normal colors for items that are not selected
e.Item.ForeColor = listView1.ForeColor;
e.Item.BackColor = listView1.BackColor;
}
e.DrawBackground();
e.DrawText();
}
Note: This solution will result in some flicker. A fix for this involves subclassing the ListView control so you
can change the protected property DoubleBuffered to true.
public class ListViewEx : ListView
{
public ListViewEx() : base()
{
this.DoubleBuffered = true;
}
}
On SelectedIndexChanged:
private void lBxDostepneOpcje_SelectedIndexChanged(object sender, EventArgs e)
{
ListViewItem item = lBxDostepneOpcje.FocusedItem as ListViewItem;
ListView.SelectedIndexCollection lista = lBxDostepneOpcje.SelectedIndices;
foreach (Int32 i in lista)
{
lBxDostepneOpcje.Items[i].BackColor = Color.White;
}
if (item != null)
{
item.Selected = false;
if (item.Index == 0)
{
}
else
{
lBxDostepneOpcje.Items[item.Index-1].BackColor = Color.White;
}
if (lBxDostepneOpcje.Items[item.Index].Focused == true)
{
lBxDostepneOpcje.Items[item.Index].BackColor = Color.LightGreen;
if (item.Index < lBxDostepneOpcje.Items.Count-1)
{
lBxDostepneOpcje.Items[item.Index + 1].BackColor = Color.White;
}
}
else if (lBxDostepneOpcje.Items[item.Index].Focused == false)
{
lBxDostepneOpcje.Items[item.Index].BackColor = Color.Blue;
}
}
}
You cant set focus on listview control in this situation. txtBarcode_Leave method will prevent this. But if you are desire to be able select listview items by clicking on them, just add code below to MouseClick event handler of listview:
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
ListView list = sender as ListView;
for (int i = 0; i < list.Items.Count; i++)
{
if (list.Items[i].Bounds.Contains(e.Location) == true)
{
list.Items[i].BackColor = Color.Blue; // highlighted item
}
else
{
list.Items[i].BackColor = SystemColors.Window; // normal item
}
}
}
This change color of selected item. but only in state listview not have focus.
Make sure HideSelection is !TRUE! and simple use this code:
private void ListView_SelectedIndexChanged(object sender, EventArgs e){
foreach(ListViewItem it in ListView.Items)
{
if (it.Selected && it.BackColor != SystemColors.Highlight)
{
it.BackColor = SystemColors.Highlight;
it.ForeColor = SystemColors.HighlightText;
}
if (!it.Selected && it.BackColor != SystemColors.Window)
{
it.BackColor = SystemColors.Window;
it.ForeColor = SystemColors.WindowText;
}
}
}
Just do like this:
Set property UnfocusedHighlighForegroundColor = "Blue"
Set property UnfocusedHighlighBackgroundColor = "White"
Set property UserCustomSelectionColors = true
Good luck :)
I'm using a CheckedListBox control in a small application I'm working on. It's a nice control, but one thing bothers me; I can't set a property so that it only checks the item when I actually check the checkbox.
What's the best way to overcome this?
I've been thinking about getting the position of the mouseclick, relative from the left side of the checkbox. Which works partly, but if I would click on an empty space, close enough to the left the current selected item would still be checked. Any ideas regarding this?
I know this thread's a bit old, but I don't think it's a problem to offer another solution:
private void checkedListBox1_MouseClick(object sender, MouseEventArgs e)
{
if ((e.Button == MouseButtons.Left) & (e.X > 13))
{
this.checkedListBox1.SetItemChecked(this.checkedListBox1.SelectedIndex, !this.checkedListBox1.GetItemChecked(this.checkedListBox1.SelectedIndex));
}
}
(With the value of CheckOnClick = True).
You could use that thingy with the rectangle, but why make it more complex the it needs to.
Well, it is quite ugly, but you could calculate mouse hit coordinates against rectangles of items by hooking on CheckedListBox.MouseDown and CheckedListBox.ItemCheck like the following
/// <summary>
/// In order to control itemcheck changes (blinds double clicking, among other things)
/// </summary>
bool AuthorizeCheck { get; set; }
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if(!AuthorizeCheck)
e.NewValue = e.CurrentValue; //check state change was not through authorized actions
}
private void checkedListBox1_MouseDown(object sender, MouseEventArgs e)
{
Point loc = this.checkedListBox1.PointToClient(Cursor.Position);
for (int i = 0; i < this.checkedListBox1.Items.Count; i++)
{
Rectangle rec = this.checkedListBox1.GetItemRectangle(i);
rec.Width = 16; //checkbox itself has a default width of about 16 pixels
if (rec.Contains(loc))
{
AuthorizeCheck = true;
bool newValue = !this.checkedListBox1.GetItemChecked(i);
this.checkedListBox1.SetItemChecked(i, newValue);//check
AuthorizeCheck = false;
return;
}
}
}
Another solution is to simply use a Treeview.
Set CheckBoxes to true, ShowLines to false, and ShowPlusMinus to false and you have basically the same thing as a CheckedListBox. The items are only checked when the actual CheckBox is clicked.
The CheckedListBox is much more simplistic, but the TreeView offers a lot of options that can potentially be better suited for your program.
I succesfully used this property:
CheckedBoxList.CheckOnClick
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.checkedlistbox.checkonclick?view=netframework-4.7.2
The text for a checkbox in a CheckedListBox is rendered by default is to place an HTML label after the checkbox input and set the label's "for" attribute to the ID of the checkbox.
When a label is denoting an element that it is "for," clicking on that label tells the browser to focus on that element, which is what you're seeing.
Two options are to render your own list with separate CheckBox controls and text (not as the Text property of the CheckBox, as that does the same thing as the CheckBoxList) if the list is static or to use something like a Repeater if the list is dynamic.
Try this. Declare iLastIndexClicked as a form-level int variable.
private void chklst_MouseClick(object sender, MouseEventArgs e)
{
Point p = chklst.PointToClient(MousePosition);
int i = chklst.IndexFromPoint(p);
if (p.X > 15) { return; } // Body click.
if (chklst.CheckedIndices.Contains(i)){ return; } // If already has focus click anywhere works right.
if (iLastIndexClicked == i) { return; } // native code will check/uncheck
chklst.SetItemChecked(i, true);
iLastIndexClicked = i;
}
Just checking to see if the user clicked in the leftmost 15 pixels of the checked list (the check box area) works at all times except re-checking a currently selected item. Storing the last index and exiting without changing lets the native code handle that properly, trying to set it to checked in that case turns it on and it just turns back off when the "ItemCheck" code runs.
I have changed the Treeview.HideSelection = false;
But how do I insure that when focus is lost that the selected item remains the original selected color?
EDIT:
I have a listview on a form that holds a list of process events. Alongside the Treeview on the same form is a series of selections that the user completes to classify the event in the listview. However, when the user makes a selection on one of the classification controls the blue highlighted selected Treeview item turns to a grey color. I was hoping to find the property that defines this color to make it the same color blue.
Any suggestions.
Update:
public partial class myTreeView : TreeView
{
TreeNode tn = null;
public myTreeView()
{
InitializeComponent();
}
protected override void OnAfterSelect(TreeViewEventArgs e)
{
if (tn != null)
{
tn.BackColor = this.BackColor;
tn.ForeColor = this.ForeColor;
}
tn = e.Node;
base.OnAfterSelect(e);
}
protected override void OnBeforeSelect(TreeViewCancelEventArgs e)
{
e.Node.BackColor = Color.Green;
e.Node.ForeColor = Color.White;
base.OnBeforeSelect(e);
}
protected override void OnGotFocus(System.EventArgs e)
{
base.OnGotFocus(e);
}
protected override void OnLostFocus(System.EventArgs e)
{
if (tn != null)
{
tn.BackColor = Color.Green;
tn.ForeColor = Color.White;
}
// tn.BackColor = Color.Red;
base.OnLostFocus(e);
}
}
Setting ListView.HideSelection to true means that when focus is lost, it will hide the selection. By setting HideSelection to false, the selected item will still have the color indicator showing which item is selected.
Generally, you don't. The change in color is one of the visual cues that indicate which control has the focus. Don't confuse your customers by getting rid of that.
If you want to buck the convention, then you can make your control owner-drawn, and then you can paint the items whatever color you want.
Another option, in your case, is to use a drop-down combo box instead of a list box. Then the current selection is always clear, no matter whether the control has the focus. Or, you could consider using a grid, where each event has all its settings given separately, and then "selection" doesn't matter at all.
If I were doing it, I would simply have an extra Label alongside the ListView, above the classification controls being selected, that would indicate which process event has been selected. You can also use said Label to add extra details about the event (if any).
This way, you are sticking to standard UI conventions and making it that much clearer to the user what their current selection is.
I use this code; it works for me.
design: Mytreeview.HideSelection = True you will manual highlight the lose focus selected node.
Private Sub MyTreeview_Leave(sender As Object, e As EventArgs) Handles MyTreeview.Leave
MyTreeview.SelectedNode.BackColor = Color.LemonChiffon
End Sub
Private Sub MyTreeview_BeforeSelect(sender As Object, e As TreeViewCancelEventArgs) Handles MyTreeview.BeforeSelect
If MyTreeview.SelectedNode IsNot Nothing Then
MyTreeview.SelectedNode.BackColor = Color.White
End Sub
I like the HideSelection = false; answer, because:
It's easy
I have a search function that cycles through the nodes and marks the relevant ones by changing it's background to yellow, when the user clicks on the node a textbox fills with the relevant info attached to that node, before I used this method, if the user clicked on the textbox to scroll through it, it would unhighlight the node and make it hard to keep track of which node was selected, this way it is still highlighted in a light gray colour showing it is not in focus, opposed to the blue highlight which is used when it is in focus. I could have 'painted' the node but with the yellow background for search results would have made life more complicated than it needed to be.
Did I mention it was easy?