5,699,997 members and growing! (25,231 online)
Email Password   helpLost your password?
Desktop Development » Combo & List Boxes » General     Intermediate License: The Code Project Open License (CPOL)

RadioListBox: A ListBox with Radio Buttons (.NET Version)

By Jaime Olivares

How to implement an owner-drawn ListBox with radio buttons instead of standard selection highlight
C#, C# 2.0Windows, .NET, .NET 2.0, WinXP, VistaVS2005, Visual Studio, Dev

Posted: 23 Apr 2007
Updated: 3 Sep 2008
Views: 54,646
Bookmarked: 71 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
24 votes for this Article.
Popularity: 6.06 Rating: 4.39 out of 5
2 votes, 8.3%
1
0 votes, 0.0%
2
1 vote, 4.2%
3
6 votes, 25.0%
4
15 votes, 62.5%
5
Screenshot - Screenshot_1.jpg

Screenshot - Screenshot_2.jpg

Introduction

This is the .NET version of my previous MFC article, CRadioListBox: A ListBox with Radio Buttons. A couple of years ago, I discussed in a Visual C++ forum about a member's request to implement a custom ListBox control similar to MFC's CCheckListBox, but with radio buttons. Initially it appeared to be trivial, since the ListBox control's unique selection version complies with the requirements, but I have concluded that this control has some advantages:

  • It is clearer that options are mutually exclusive with radio buttons.
  • It is a good alternative to a group of radio buttons because you have to maintain just one control, less memory use.
  • It inherits some useful features like scrolling, sorting, data binding and multi-column.
  • It will be easier to change options dynamically, as shown in the demo application.
  • It will be easier to manage selection events, also shown in the demo application.

Using the Code

To implement RadioListBox into your project, you just need to do a few steps:

  • Include RadioListBox.cs into your project.
  • Drop a RadioListBox object into your form.
  • Change the standard properties of the control, just like a ListBox.
  • Countersense to standard ListBox, transparent BackColor property is allowed.

That's all! Now you can use the radio button collection as a regular ListBox. You can add items with the Items.Add() method and query for user selection with the SelectedIndex property.

Fake Transparency

Some .NET controls accept a transparent color as a BackColor property, but ListBox is not one of them. So, transparency requires lots of non-managed tricks. However, transparency is a key feature needed for this control to be useful. It allows the control to acquire a real radio button look and feel, as you can see in the screenshot above. I decided to stay in the managed world by providing fake transparency to the control by overriding the BackColor property to accept it, and saving its own background color brush. When setting the background color to transparent, the control will mimic the parent form or control, even if the form has a non-standard background color.

RadioListBox Internals

The RadioListBox class is derived from Windows Forms' ListBox class with the owner-draw feature. The resumed class definition is the following:

using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms.VisualStyles;

namespace System.Windows.Forms
{
    public class RadioListBox : ListBox
    {
        private StringFormat Align;
        private bool IsTransparent = false;  // Handles the transparent state
        private Brush BackBrush;  // Manages its own background brush

        // Allows the BackColor to be transparent
        public override Color BackColor ...

        // Hides these properties in the designer
        [Browsable(false)]
        public override DrawMode DrawMode ...

        [Browsable(false)]
        public override SelectionMode SelectionMode ...

        // Public constructor
        public RadioListBox() ...

        // Main painting method
        protected override void OnDrawItem(DrawItemEventArgs e) ...

        // Prevent background erasing
        protected override void DefWndProc(ref Message m) ...

        // Other event handlers
        protected override void OnHandleCreated(EventArgs e) ...
        protected override void OnFontChanged(EventArgs e) ...
        protected override void OnParentChanged(EventArgs e) ...
        protected override void OnParentBackColorChanged(EventArgs e) ...
    }
}

The core enhancement is at the OnDrawItem() method. The method does not highlight the selected item as in a standard ListBox control, but draws a radio button instead. It also manages the focus state to draw the focus rectangle properly and the background color according to the transparency attribute. Here is the C# source code:

// Main painting method
protected override void OnDrawItem(DrawItemEventArgs e)
{
    int maxItem = this.Items.Count - 1;

    if (e.Index < 0 || e.Index > maxItem)
    {
        // Erase all background if control has no items
        e.Graphics.FillRectangle(BackBrush, this.ClientRectangle);
        return;
    }

    int size = e.Font.Height; // button size depends on font height, not on item height

    // Calculate bounds for background, if last item paint up to bottom of control
    Rectangle backRect = e.Bounds;
    if (e.Index == maxItem)
        backRect.Height = this.ClientRectangle.Top + 
        this.ClientRectangle.Height - e.Bounds.Top;
    e.Graphics.FillRectangle(BackBrush, backRect);

    // Determines text color/brush
    Brush textBrush;
    bool isChecked = (e.State & DrawItemState.Selected) == DrawItemState.Selected;

    RadioButtonState state = isChecked ? 
        RadioButtonState.CheckedNormal : RadioButtonState.UncheckedNormal;
    if ((e.State & DrawItemState.Disabled) == DrawItemState.Disabled)
    {
        textBrush = SystemBrushes.GrayText;
        state = isChecked ? RadioButtonState.CheckedDisabled : 
                RadioButtonState.UncheckedDisabled;
    }
    else if ((e.State & DrawItemState.Grayed) == DrawItemState.Grayed)
    {
        textBrush = SystemBrushes.GrayText;
        state = isChecked ? RadioButtonState.CheckedDisabled : 
                RadioButtonState.UncheckedDisabled;
    }
    else
    {
        textBrush = SystemBrushes.FromSystemColor(this.ForeColor);
    }

    // Determines bounds for text and radio button
    Size glyphSize = RadioButtonRenderer.GetGlyphSize(e.Graphics, state);
    Point glyphLocation = e.Bounds.Location;
    glyphLocation.Y += (e.Bounds.Height - glyphSize.Height) / 2;

    Rectangle bounds = new Rectangle(e.Bounds.X + glyphSize.Width, e.Bounds.Y, 
        e.Bounds.Width - glyphSize.Width, e.Bounds.Height);

    // Draws the radio button
    RadioButtonRenderer.DrawRadioButton(e.Graphics, glyphLocation, state);

    // Draws the text
    // Bound Datatable? Then show the column written in Displaymember   
    if (!string.IsNullOrEmpty(DisplayMember)) 

        e.Graphics.DrawString(((System.Data.DataRowView)this.Items[e.Index])
            [this.DisplayMember].ToString(),
        e.Font, textBrush, bounds, this.Align);
    else
        e.Graphics.DrawString(this.Items[e.Index].ToString(), 
            e.Font, textBrush, bounds, this.Align);

    // If the ListBox has focus, draw a focus rectangle around the selected item.
    e.DrawFocusRectangle();
}

History

  • 23rd April, 2007: First version
  • 14th September, 2007: Refinements in control rendering (thanks to stephpms); support for bounded data (thanks to PeterDP)
  • 1st September, 2008: Improved background painting; support for large fonts (thanks to rkousha)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Jaime Olivares




Computer Electronics professional and senior Windows C++ and C# developer with experience in many other programming languages, platforms and application areas including communications, simulation systems, GIS, graphics and mobile issues.
Also have experience in electronic interfaces development, specially for military applications.
Currently intensively working with Visual C# 2008.
Top-100 contributor at Experts-Exchange forum.
If you have an interesting project, you can contact him at: jaimeolivares.com
Occupation: Software Developer (Senior)
Company: Freelance contractor
Location: Peru Peru

Other popular Combo & List Boxes articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 27 (Total in Forum: 27) (Refresh)FirstPrevNext
GeneralHow binds List to RadioButtonListmemberWeb Star21:39 17 Apr '08  
GeneralRe: How binds List to RadioButtonListmemberJaime Olivares7:51 18 Apr '08  
QuestionIt would be cool to support fade-in & fade-out while mouse hovering, just like common controls on vista.memberMember 16223979:05 21 Dec '07  
QuestionIt would be cool to support fade-in & fade-out while mouse hovering, just like common controls on vista.memberMember 16223979:05 21 Dec '07  
GeneralRe: It would be cool to support fade-in & fade-out while mouse hovering, just like common controls on vista.memberJaime Olivares7:24 22 Jan '08  
Generalplz help!!!membersilver_fish8:20 13 Nov '07  
GeneralRe: plz help!!!memberRi Qen-Sin8:48 13 Nov '07  
Generalthanksmemberk_hammami200523:16 30 Sep '07  
GeneralProblem with radio control Font changememberrkousha1:27 23 Sep '07  
AnswerRe: Problem with radio control Font changememberJaime Olivares9:22 1 Oct '07  
GeneralThanksmembershri_khamitkar21:50 9 Jul '07  
GeneralDisplaying the displaymembermemberPeterDP7:26 3 Jul '07  
GeneralRe: Displaying the displaymembermemberPeterDP23:06 3 Jul '07  
GeneralUse new radioButton style...memberstephpms23:53 25 Jun '07  
GeneralThe LookmemberDEGT8:07 1 Jun '07  
AnswerRe: The LookmemberJaime Olivares17:16 10 Jun '07  
GeneralRe: The LookmemberDEGT23:53 10 Jun '07  
GeneralTrouble with implementingmemberOldek6:17 26 May '07  
GeneralClass not publicmemberRudolf Jan Heijink5:02 5 May '07  
GeneralRe: Class not publicmemberJaime Olivares18:19 5 May '07  
QuestionHow can I make this list a MultiColumnList???memberhamidhussain22:38 1 May '07  
AnswerRe: How can I make this list a MultiColumnList???memberJaime Olivares8:20 2 May '07  
AnswerRe: How can I make this list a MultiColumnList???memberJaime Olivares18:12 5 May '07  
AnswerRe: How can I make this list a MultiColumnList???memberlehoangtrung4:10 10 May '07  
AnswerRe: How can I make this list a MultiColumnList???memberJaime Olivares9:58 14 May '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 3 Sep 2008
Editor: Deeksha Shenoy
Copyright 2007 by Jaime Olivares
Everything else Copyright © CodeProject, 1999-2008
Web17 | Advertise on the Code Project