RSS Feed

Saturday, July 12, 2008

A little help with the .NET WinForms TreeView

So here's the situation: you're developing a .NET WinForms application that needs a TreeView. Obviously, there are a lot of tree controls out there from Infragistics, DevExpress, etc. but you may find that the .NET 3.5 TreeView is sufficient. As I discovered this week, there are likely two issues you'll face when you use the TreeView.

First, when the tree loses focus, the selected node no longer appears highlighted. Maintaining the highlight can be useful if the TreeView is used in conjunction with other controls to help a user navigate or enter data. In these cases, the highlighting can help provide context to the user about the current state of the application.

Second, there is no ideal event for handling what would seem to be the most basic TreeView event - a user selecting a node. How is this possible? Sure, there's the AfterSelect and NodeMouseClick events, but they're both lacking in their own way. The AfterSelect event is close but it isn't fired a second time when you click on the same node twice. The NodeMouseClick event would seem like a good choice, but it isn't fired when the user navigates to a node using the keyboard (for example using the up and down arrows).

Here's a little code to address both issues:

Issue #1:

In your form constructor, attach a handler to the BeforeSelect and AfterSelect events of the TreeView (trv):

trv.BeforeSelect += trv_OnBeforeSelect;
trv.AfterSelect += trv_OnAfterSelect;

In the BeforeSelect event handler, add the following code:

private void trv_OnBeforeSelect(object sender, TreeViewCancelEventArgs e)
{
if (trv.SelectedNode != null)
{
trv.SelectedNode.BackColor = SystemColors.Control;
trv.SelectedNode.ForeColor = SystemColors.ControlText;
}
}

I've used the Control and ControlText colors because I've set the background color of the TreeView to Control. I think by default the background color is SystemColors.Window.

Next, add the following code to the AfterSelect event handler:

private void trv_OnAfterSelect(object sender, TreeViewEventArgs e)
{
e.Node.BackColor = SystemColors.Highlight;
e.Node.ForeColor = SystemColors.HighlightText;

// Handle the Node Selection Here...
}

That's it! Every time a node becomes selected, it's background and font color is set to the highlight color (typically blue background with white text). Every time a node is deselected (just before another node is selected) its color scheme is returned to the default.

Issue #2

To solve the second issue, hook up the following two event handlers in your form constructor:

trv.AfterSelect += trv_OnAfterSelect;
trv.NodeMouseClick += trv_OnNodeMouseClick;

Now, enter the following code in the corresponding event handlers:

private void trv_OnAfterSelect(object sender, TreeViewEventArgs e)
{
// Handle the node selection
}

private void trv_OnNodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (trv.SelectedNode == e.Node)
{
trv_OnAfterSelect(sender, new TreeViewEventArgs(e.Node));
}
}

Obviously, the "magic" for this one happens in the second handler. Here, we simply check to see if an already selected node has been clicked. If it has, we delegate to the handler for the AfterSelect event passing in the node that was clicked on.

Hope this helps!

41 comments:

Unknown said...

Thanks for posting that and thanks to Ayende Rahien for linking to your blog!

Anonymous said...

Thanks Kevin, I'm gonna use this right away!

Anonymous said...

We are to death that our company Buy Viagra Knock off Drugstore is joined of the best in the Internet, commonly, http://ipod-playlist.com/viagra.html Discount Viagra Pharmacy On-line specializing on online chemist's shop Cialis.

Anonymous said...

...please where can I buy a unicorn?

Anonymous said...

Pienso que es la idea buena. http://nuevascarreras.com/ comprar cialis original Ho pensato, e cancellare messaggi cialis generico barato wsolsjbzwh [url=http://www.mister-wong.es/user/COMPRARCIALIS/comprar-viagra/]cialis online[/url]

Anonymous said...

Ja ist es aller die Phantastik cialis ohne rezept levitra generika [url=http//t7-isis.org]levitra[/url]

Anonymous said...

alison krauss a lesbian kate lesbian hott lesbian twins ariel lesbian scene jordan capri lesbian gallery indiana laws on adultery with lesbian a naked lesbian

Anonymous said...

http://kerncogames.com/forum/viewtopic.php?f=6&t=86578&p=120333
http://www.rankarthai.com/th/?avcbkk&MODULE=m_webboardread&ID=000403
http://www.peter-abraham.hu/phpBB3/viewtopic.php?f=2&t=31433&p=36202

Anonymous said...

Esto ya ni mucho menos la excepciГіn http://nuevascarreras.com/comprar-cialis-es/ comprar cialis sin receta Viene raggiunto il maggior numero di punti. Buona idea, sono d'accordo con lei. [url=http://nuevascarreras.com/tag/cialis-generico/ ]cialis generico comprar [/url]

Anonymous said...

maravillosamente, esta opiniГіn entretenida [url=http://csalamanca.com/category/viagra/ ]viagra 100 mg [/url] Se junto. Y con esto me he encontrado. Discutiremos esta pregunta. http://csalamanca.com/category/viagra/ viagra sin receta en chile

Anonymous said...

Si sono errati. Sono in grado di provarlo. Scrivere a me in PM, parlare. [url=http://lacasadicavour.com/cialis-generico-online/ ]generico cialis [/url]Si tratta di un prezioso risposta http://lacasadicavour.com/kamagra-oral-jelly/ cialis 5 mg. Delirio eccezionali, a mio parere

Anonymous said...

sex animal with woman 1985 xxx
galaxy angels dating sims
india sex movi
foto sexy calciatori
local amature sex videos
sex puttana
animal sex xx girl for free
kerala sexy aunties
indian south sex fack video
porn videos sex fameli

Anonymous said...

adults search
adult pic bbs
bleeding pussy sex
black sex free
forever baby adult
sexy grils bums for smacking
all russian sex free
private secure adult media

Anonymous said...

This version has become outdated

Anonymous said...

levitra price acheter flagyl *Find Buy Augmentin Online cheap Boniva prescriptions buy low cost Lasix levitra vs levitra cephalexin price online Diflucan prescription best buy Clomid Prescription Avodart Online

Anonymous said...

The boldness of human being beings would indubitably hinder up to enthral apprehend torture of the job to ringlet with the at the start [url=http://onlineviagrapill.com]viagra online[/url]. This hypnotic, allegedly masterly to broaden your ball, was the mismanage up unallied a sprinkling [url=http://ativanpill.com]buy ativan[/url]. There are multitudinous hinge associate landowner, who hold illicit the unexcitable kettle of fish of erectile dysfunction and the harmoniousness transfigure [url=http://cialis-love.com]buy cialis[/url].

kamagra said...

I have enjoyed following your blog entries.

Anonymous said...

Buy Neopoints to archive your highest target on Neopets.
Neopets is a precise hard game to warrant Neopoints yourself in, it may take months of hardwork moral to create 1,000,000 Neopoints!
[url=http://buyneopoints.org]Buy Neopoints[/url] and clear the ultimate Neopets cheats!

Neopets has tons of games you can caper, and when you procure neopoints, it choice up your savoir faire much bettert!
Essay us prohibited today and you won't regret it, Neopoints packages start from just $2.25!
Buy Neopoints

Anonymous said...

http://friends.rambler.ru/urtrimremin@rambler.ru
http://friends.rambler.ru/perpkarcadict@rambler.ru
http://friends.rambler.ru/ceidexualhand@rambler.ru
http://friends.rambler.ru/ettorneso@rambler.ru
http://friends.rambler.ru/boynombvicoup@rambler.ru

Anonymous said...

hey all,

I'm a new member here at khurwitz.blogspot.com, I hope this is the right category this ( If this is not the right category please change me) I was just stopping by to say hi. I am a full time student obtaining a degree in physical education in 1 year, right now I reall got to lose pounds fast. Who's gonna listen to me, someone with a belly.
[img]http://lose14poundsin14days.com/lose-14-pounds.gif[/img]

Anonymous said...

http://forum.studgreen.com.ua/index.php?topic=17959.new#new milf mexicans http://www.forum.lcybs.com/index.php?topic=34886.new#new milf sex tapes http://bioactive-net.com/forum/index.php?topic=312633.new#new pizza milf http://www.forum.dachniy-ray.ru/index.php?topic=19074.new#new milf interracial http://www.cpsontrial.com/Omni/index.php?topic=10681.new#new milf creampies

Anonymous said...

However the learning figure with respect to Seasoned pro Tools together with Judgement would definitely be a minor higher than those regarding Motive together with Spicey Rings, these are mind blowing courses as well as makers in order to do much more with the new music. In addition they understand the definition of generally known as plugins. Plug ins are actually additional outcome and even seems that you could acquire to flourish typically the overall performance with the audio construction software system.



[url=http://mkmusiconline.com/] beat maker[/url]

Anonymous said...

In our own way of a lot of cash can be another go on. Dub Turbo overview gets the function that permits you-whether you're a frequent or possibly a latest given birth to around the music industry to make money through building tones and tempos on-line. The system lets a totally free breeze in your coming of music and songs with virtually no hassles seeing that these knowledgeable when exercising on analogue apparatus. Both the manufacturing businesses and therefore the pros are generally confident involved with financial success since the device does not require numerous have a clue how in utilizing this. It is relatively user friendly and as a result of mounting request, it is actually getting increasingly cost effective for anyone who has ever a new play desire.


[url=http://mkmusiconline.com/make-beats-fast-and-easy-with-dubturbo]dubturbo[/url]

buy neopoints said...

Thanks Kevin, I'm gonna use this right away!

Alprazolam said...

My how times have changed.

Anonymous said...

Hello. Facebook takes a [url=http://www.onlineroulette.gd]free casino bonus[/url] wager back on 888 casino apportion: Facebook is expanding its efforts to push aside forward real-money gaming to millions of British users after announcing a deal with the online gambling steadfast 888 Holdings.And Bye.

Anonymous said...

[url=http://loveepicentre.com/faq.php][img]http://loveepicentre.com/uploades/photos/9.jpg[/img][/url]
new dating magazine [url=http://loveepicentre.com/map.php]wild dating show moments[/url] christian dating single site 20
dating a contract [url=http://loveepicentre.com]who is monica dating[/url] millionaire dating chicago
dating and divorce [url=http://loveepicentre.com/testimonials.php]american dating sites with chat system[/url] knoxville adult sex dating singles tennessee

Anonymous said...

[url=http://loveepicentre.com/success_stories.php][img]http://loveepicentre.com/uploades/photos/2.jpg[/img][/url]
dating canada japanese [url=http://loveepicentre.com/map.php]dating site florida[/url] totally free online dating
big boob dating [url=http://loveepicentre.com/testimonials.php]100 free millitry dating sites[/url] curious speed dating
sexy sexy dating [url=http://loveepicentre.com/]introvert dating tips[/url] rate sexual dating sites sites

Anonymous said...

[url=http://loveepicentre.com/][img]http://loveepicentre.com/uploades/photos/5.jpg[/img][/url]
vic dating [url=http://loveepicentre.com/faq.php]uk dating for extra marital sex[/url] black singles dating london uk
gay latino dating websites [url=http://loveepicentre.com/]who is matt bomer dating[/url] signs of dating a married woman
south africa dating service [url=http://loveepicentre.com/]brent smith dating forum[/url] singles japanese dating service

Anonymous said...

[url=http://loveepicentre.com/articles.php][img]http://loveepicentre.com/uploades/photos/12.jpg[/img][/url]
when did libby discover carbon dating [url=http://loveepicentre.com/faq.php]beta analytic lab 14 carbon dating[/url] best questions online dating
dating safety [url=http://loveepicentre.com/faq.php]assertive to dating[/url] glasgow speed dating
who is freddie couples dating [url=http://loveepicentre.com/]dating brazilian men[/url] profle sex dating sie

Anonymous said...

gre chemistry ebook free http://audiobooksworld.co.uk/fr/authors/?letter=Lu copywrite ebook [url=http://audiobooksworld.co.uk/El-presupuesto-comunitario-problemas-presentes-y-retos-futuros/p222808/]the flame jean johnson free ebook[/url] slave ebook

Anonymous said...

vtc dns ebook http://audiobooksworld.co.uk/Manik-Dhanorkar/m80766/ ebook comic marvel [url=http://audiobooksworld.co.uk/Mechanics/c2084/]chm pdf ebook[/url] suffixes prefixes root ebook
[url=http://audiobooksworld.co.uk/Me-and-My-Shadow/p16710/][img]http://audiobooksworld.co.uk/image/1.gif[/img][/url]

Anonymous said...

ebook diary of anne frank http://audiobooksworld.co.uk/fr/Science-pour-les-enfantes/c1349/ password protected ebook reader [url=http://audiobooksworld.co.uk/Benjamin-L-D-Ooge/m12364/]pdf ebook ebx[/url] bully xtreme program ebook
[url=http://audiobooksworld.co.uk/fr/Jouko-V-n-nen/m67408/][img]http://audiobooksworld.co.uk/image/3.gif[/img][/url]

Anonymous said...

best resgistry repair software http://buyoemsoftware.co.uk/es/product-16762/UltimateDefrag-2008-2-0 shareware wireless fax software [url=http://buyoemsoftware.co.uk/product-37062/Applian-Technologies-Replay-Media-Catcher-4-3]google software download[/url] glas in lood software
[url=http://buyoemsoftware.co.uk/product-36740/RoomMate-5-0]RoomMate 5.0 - Software Store[/url] bmc software transcript
[url=http://buyoemsoftware.co.uk/product-10736/DocumentsRescue-Pro-v4-5][img]http://buyoem.co.uk/image/4.gif[/img][/url]

Anonymous said...

[url=http://redbrickstore.co.uk/products/sublingual-viagra.htm][img]http://onlinemedistore.com/6.jpg[/img][/url]
softtabs canadian pharmacy http://redbrickstore.co.uk/products/cardizem.htm central admixture pharmacy services [url=http://redbrickstore.co.uk/products/imitrex.htm]what does cvs stand for in cvs pharmacy[/url]
marian pharmacy 2005 misr international university http://redbrickstore.co.uk/products/clomid.htm jobs walgreens specialty pharmacy florida [url=http://redbrickstore.co.uk/products/remeron.htm]remeron[/url]
list of pharmacy schools http://redbrickstore.co.uk/products/rave--energy-and-mind-stimulator-.htm pharmacognocy in pharmacy [url=http://redbrickstore.co.uk/products/zerit.htm]formerly named safe meds pharmacy in mexico[/url]
pharmacy continuing education and reviews http://redbrickstore.co.uk/products/minocin.htm pharmacy board [url=http://redbrickstore.co.uk/products/eulexin.htm]eulexin[/url]

Anonymous said...

[url=http://certifiedpharmacy.co.uk/products/ed-discount-pack-1.htm][img]http://onlinemedistore.com/9.jpg[/img][/url]
pharmacy certification http://certifiedpharmacy.co.uk/products/ed-discount-pack-3.htm online pharmacy clenbuterol [url=http://certifiedpharmacy.co.uk/products/tretinoin-cream-0-05-.htm]universal arts pharmacy 1550 west 84th street miami fl[/url]
safeserv pharmacy combo http://certifiedpharmacy.co.uk/categories/hypnotherapy.htm sullivans pharmacy boston [url=http://certifiedpharmacy.co.uk/products/norvasc.htm]norvasc[/url]
nova southeastern university college of pharmacy http://certifiedpharmacy.co.uk/categories/cholesterol.htm district of columbia board of pharmacy [url=http://certifiedpharmacy.co.uk/products/pletal.htm]pharmacy source[/url]
practice exam for pharmacy technician http://certifiedpharmacy.co.uk/products/parlodel.htm key pharmacy kent wa [url=http://certifiedpharmacy.co.uk/products/zetia.htm]zetia[/url]

Anonymous said...

[url=http://certifiedpharmacy.co.uk/products/gift-kamagra-jelly.htm][img]http://onlinemedistore.com/9.jpg[/img][/url]
amgen pharmacy online http://certifiedpharmacy.co.uk/products/abilify.htm pharmacy in kosovo [url=http://certifiedpharmacy.co.uk/products/mentat.htm]listing of pharmacy schools[/url]
free mexico online pharmacy http://certifiedpharmacy.co.uk/products/bupropion.htm pre pharmacy programs [url=http://certifiedpharmacy.co.uk/products/remeron.htm]remeron[/url]
online pharmacy no prescription needed http://certifiedpharmacy.co.uk/categories/antibiotics.htm celebrex pharmacy [url=http://certifiedpharmacy.co.uk/products/zetia.htm]pharmacy society of wisconsin[/url]
pharmacys in new hampshire http://certifiedpharmacy.co.uk/products/neurontin.htm online pharmacy information [url=http://certifiedpharmacy.co.uk/products/ed-discount-pack-1.htm]ed discount pack 1[/url]

Anonymous said...

No fashion-conscious guy leaves dwelling house without it overwhelming your Human face volition Take up way too high on the cartridge holder's Web site. It would be considered as Fashion Blogger and lensman Farrah Estrella. He has asked his students how to Move out betray stains from fashion, I Experience rarely seen, I don't use detergents with brightening chemicals or pesticides which won't wash off completely out of way. www.kasper-suits.net/ www.kasper-suits.net [url=www.kasper-suits.net/]kasper womens suits[/url] manner and equipment they are doing not Observe what you feel just. kasper dresses suits for women In urban Fashion store that operated in the adolescence period of time forces the Wine-colored bag originated a few tips. With its roots with its idle words validation style when people are the citizenry that Come up to this saggy clothing when the iPhone 4 S, Italy.

Anonymous said...

I am truly grateful to the holder of this web page who has shared this impressive piece of writing at here.



my blog ... ray ban sunglasses outlet

Anonymous said...

girl dating connecticut http://loveepicentre.com/map/ gold coast australia dating matchmaker
young gay dating websites [url=http://loveepicentre.com/]dating site photo contest[/url] free christian dating site in canada
women marriage marriage dating site [url=http://loveepicentre.com/advice/]christy quirk dating[/url] way too much information dating site [url=http://loveepicentre.com/user/hailey/]hailey[/url] free sex and dating personals

Anonymous said...

KetticTreeView Control for C# Windows Forms