I'm using a treeview-control in winforms and an imagelist to display different states of the treeview-elements.
But i don't want to use the selected element to use a different image.
Is there a way to disable SelectedImageIndex in the TreeView-control?
If tried to change the selectedimageindex after every selection. Something like this:
private void TreeView1AfterSelect(object sender, TreeViewEventArgs e)
{
treeView1.SelectedImageIndex = treeView1.SelectedNode.ImageIndex;
}
But this causes a pretty ugly flickering of the control after every selection..
When you are creating the new TreeNode, assign the same imageindex to ImageIndex and SelectedImageIndex:
...
node.SelectedImageIndex = node.ImageIndex;
...
When creating the node
Dim nd As New TreeNode("NodeKey", "NodeText", 1, 1)
The two indices are for ImageIndex and SelectedImageIndex.
Related
I am using Combo box while creating Desktop Application using C# in Visual Studio, I increased the font size to "20" now when I run the application and click the dropdown button list elements font-size also increased.
That's fine. But, when I write something in the combo box it gives suggestions as shown in the picture below.
I, also want to increase the font size of this suggestion list, I have set "AutoCompleteMode" property set to "suggest". Is anybody can help me with this?
The font of the auto-complete text presented is fixed. There is no corresponding properties to set it.
A workaround is that you can create a custom control and replace the suggest-drop-down with custom listbox.
public Form1()
{
InitializeComponent();
comboBox1.Size = new Size(120, 30);
listBox.SelectedIndexChanged += ListBox_SelectedIndexChanged;
}
private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox1.Text = listBox.Text;
listBox.Visible = false;
}
ListBox listBox = new ListBox();
// event triggered when the user enters text
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
// set the font of listbox to be consistent with combobox
listBox.Font = comboBox1.Font;
// add listbox below combobox
listBox.Location = new Point(comboBox1.Location.X, comboBox1.Location.Y + comboBox1.Height);
// filter suggest items
listBox.Items.Clear();
foreach (string item in comboBox1.Items)
{
if (item.StartsWith(comboBox1.Text) && comboBox1.Text != string.Empty)
{
listBox.Items.Add(item);
}
}
listBox.Visible = listBox.Items.Count > 0;
this.Controls.Add(listBox);
}
Test result:
Those are actually two areas which you can configure independently. According to this MSDN article,
To change settings:
Go to Tools – Options – Environment - Fonts and Colors
Under Show settings for: select either Statement Completion or Editor Tooltips (for Parameter Info and Quick Tips)
Change either the font or font size
I have a ListView which displays multiple rows of ListViewItems. The user is able to edit one of these items through a dialog which opens after clicking 'Edit.' When the dialog closes I would like to modify the selected ListViewItem such that it reflects the new settings.
Here is how I currently update my item:
private void btnEditSnmpV3Setting_Click(object sender, EventArgs e)
{
if (lstVwSNMPv3Settings.SelectedItems.Count > 0)
{
ListViewItem selectedItem = lstVwSNMPv3Settings.SelectedItems[0];
NetworkDiscoverySnmpSetting settings = (NetworkDiscoverySnmpSetting)selectedItem.Tag;
NetworkDiscoverySnmpV3SettingsDialog dialog = new NetworkDiscoverySnmpV3SettingsDialog(settings);
//Pass in the owner for centering of dialog.
if (dialog.ShowDialog(this) == DialogResult.OK)
{
selectedItem.SubItems.Clear();
selectedItem.Text = settings.SnmpV3Username;
selectedItem.SubItems.Add(settings.SecurityMode.ToString());
selectedItem.SubItems.Add(settings.AuthenticationProtocol.ToString());
selectedItem.SubItems.Add(settings.PrivacyProtocol.ToString());
selectedItem.Tag = settings;
}
}
}
I found this to be a poor solution due to the fact that I need to touch code in multiple places if my ListView's number of columns changes.
I handled this code-reuse issue during the 'Add' event (as opposed to 'Edit') by giving NetworkDiscoverySnmpSetting a utility method:
public ListViewItem ToListViewItem()
{
ListViewItem listViewItem = new ListViewItem();
listViewItem.Text = SnmpV3Username;
listViewItem.SubItems.Add(SecurityMode.ToString());
listViewItem.SubItems.Add(AuthenticationProtocol.ToString());
listViewItem.SubItems.Add(PrivacyProtocol.ToString());
listViewItem.Tag = this;
return listViewItem;
}
which is used like so:
private void btnAddSnmpV3Setting_Click(object sender, EventArgs e)
{
NetworkDiscoverySnmpSetting settings = new NetworkDiscoverySnmpSetting(NetworkDiscovery.ID);
NetworkDiscoverySnmpV3SettingsDialog dialog = new NetworkDiscoverySnmpV3SettingsDialog(settings);
//Pass in the owner for centering of dialog.
if (dialog.ShowDialog(this) == DialogResult.OK)
lstVwSNMPv3Settings.Items.Add(settings.ToListViewItem());
}
Unfortunately, ListView.SelectedItems does not allow collection-modification. As such, this does not compile:
lstVwSNMPv3Settings.SelectedItems[0] = settings.ToListViewItem();
How should I change my first code-snippet so that I do not need to update my code in multiple places when ListView's columns change?
You can modify the element itself rather than replacing it with another one, because ListViewItem is a class, so it's a reference type.
In order to do this follow these steps:
get currently selected item and save it to variable like this: ListViewItem selectedItem = lstVwSNMPv3Settings.SelectedItems[0];
modify your ToListViewItem method to void ToListViewItem(ListViewItem listViewItem) (return void and take ListViewItem object as parameter and modify it instead of creating a new object. It should also rather modify properties of existing subitems than creating new ones. It can look more or less like this:
public void ToListViewItem(ListViewItem listViewItem)
{
listViewItem.Text = SnmpV3Username;
listViewItem.SubItems[0].Text = SecurityMode.ToString();
listViewItem.SubItems[1].Text = AuthenticationProtocol.ToString();
listViewItem.SubItems[2].Text = PrivacyProtocol.ToString();
listViewItem.Tag = this;
}
call ToListViewItem(selectedItem);
you don't have to assign the modified item back to the collection, because you use a reference, which means you've just modify the same object that's in the ListView
I did a quick test and the method seems to modify texts of existing items without issues.
ListViewItems have a bool Selected property that you can toggle to make them selected or not selected.
A much simpler solution, that worked for me:
lstVwSNMPv3Settings.Items[lstVwSNMPv3Settings.SelectedIndices[0]] = myNewItem;
But be careful to first make sure there is an item selected:
if (lstVwSNMPv3Settings.SelectedIndices.Count > 0) { ... }
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 have a treeView with many nodes. I want that some nodes change their image when node collapsed/expanded. How can I do it ?
Unfortunately, TreeNode don't have properties like ExpandNodeImage, CollapseNodeImage \
TreeView can change very often, so nodes can be deleted/added.. i can delete child nodes and so on...
Maybe, there is a class like ExpandAndCollapseNode ?
1). Add an ImageList Control to your WinForm.
2). Populate the ImageList with the pictures/icons you wish to change/display in response to what the user does at run-time with the TreeView, such as expanding, or collapsing nodes.
3). Assign the 'ImageList Control to the 'ImageList property of the 'TreeView
At this point you may want to make an initial pass over the TreeView, assuming it is populated, assigning the Node.ImageIndex property to point to the Image ... in the ImageList ... you want to use for the Node depending on whether it has children, or whatever.
4). If a user expands a Node, for example, you can use the BeforeExpand Event of the TreeView to change the Node's picture : like so : in this case we use the index of the Picture in the ImageList :
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
e.Node.ImageIndex = 3;
}
5) You can also set the Node's image by using the ImageKey property which is the string name of the Image
6) There lots of other possible Node Picture variations to use : check out : SelectedImageIndex and SelectedImageKey : You can change Node pictures in the BeforeSelect, AfterSelect and BeforeExpand, events also, depending on the effect you are after.
BeforeCollapse
BeforeExpand
AfterCollapse
AfterExpand
Use both ImageIndex & SelectedImageIndex:
private void treeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
e.Node.ImageIndex = 1;
e.Node.SelectedImageIndex = 1;
}
TreeViews have the following events that will be be fired when nodes are collapsed/expaned.
BeforeCollapse
BeforeExpand
AfterCollapse
AfterExpand
It's better to use :
treeNode.SelectedImageIndex = 1;
you can use the events AfterCollapse & AfterExpand (that are avilable on the TreeView itself) to modify the image of a node.
you can get the node using the TreeViewEventArgs input parameter:
private void treeView1_AfterCollapse(object sender, TreeViewEventArgs e)
{
e.Node.ImageIndex = 1;
}
I want to use a ComboBox with the DropDownList style (the one that makes it look like a button so you can't enter a value) to insert a value into a text box. I want the combobox to have a text label called 'Wildcards' and as I select a wildcard from the list the selected value is inserted in to a text box and the combobox text remains 'Wildcard'. My first problem is I can't seem to set a text value when the combobox is in DropDownList style. Using the properties pallet doesn't work the text value is simply cleared when you click off, adding comboBox.Text = "Wildcards"; to form_load doesn't work either. Can anyone help?
The code you specify:
comboBox.Text = "Wildcards";
...should work. The only reason it would not is that the text you specify is not an item within the comboBox's item list. When using the DropDownList style, you can only set Text to values that actually appear in the list.
If it is the case that you are trying to set the text to Wildcards and that item does not appear in the list, and an alternative solution is not acceptable, you may have to be a bit dirty with the code and add an item temporarily that is removed when the drop-down list is expanded.
For example, if you have a form containing a combobox named "comboBox1" with some items and a button named "button1" you could do something like this:
private void button1_Click(object sender, EventArgs e)
{
if (!comboBox1.Items.Contains("Wildcards"))
{
comboBox1.Items.Add("Wildcards");
}
comboBox1.Text = "Wildcards";
}
private void comboBox1_DropDown(object sender, EventArgs e)
{
if (comboBox1.Items.Contains("Wildcards"))
comboBox1.Items.Remove("Wildcards");
}
That's pretty quick and dirty but by capturing the DropDownClosed event too you could clean it up a bit, adding the "Wildcards" item back as needed.
You can select one of items on formload or in form constructor:
public MyForm()
{
InitializeComponent();
comboBox.SelectedIndex = 0;
}
or
private void MyForm_Load(object sender, EventArgs e)
{
comboBox.SelectedIndex = 0;
}
Try this
comboBox1.SelectedValue = "Wildcards";
This may be a possible solution:
comboBox1.SelectedValue = comboBox1.Items.FindByText("Wildcards").Value;