Click here to Skip to main content
6,634,665 members and growing! (15,941 online)
Email Password   helpLost your password?
Desktop Development » Combo & List Boxes » General     Intermediate

An editable multi-line listbox for .NET

By Nishant Sivakumar

An owner drawn listbox that supports multi-line word-wrapped text as well as in-place editing.
C#, Windows, .NET 1.0, Dev
Posted:4 Aug 2002
Views:240,802
Bookmarked:64 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
39 votes for this article.
Popularity: 6.80 Rating: 4.27 out of 5
2 votes, 6.3%
1

2
2 votes, 6.3%
3
5 votes, 15.6%
4
23 votes, 71.9%
5

Overview

MultiLineListBox is a fully owner drawn ListBox derived class that supports multi-line items as well as in-place editing of items. It has been wrapped into a class library for ease of deployment. You don't have to do anything special when using it. Just use it as you would use a normal list box. Whenever you add a string that's too long for a single line, the MultiLineListBox will wrap the long string into multiple lines. Editing items is also easy. Just right click on any item or press the F2 key when an item is selected, this will superimpose an edit box exactly on top of the selected or clicked item. You can make your changes and either press the Enter key or you can click anywhere else within the list box for the modifications to take effect. If you want to cancel the changes and get back to the original text, simply hit the Escape key.

The class will not allow you to make an item null, and will pop up a message box alert and won't let you take focus away from the item till you've either cancelled the modification by pressing Escape or you have entered some text.

If you enter a lot of text into the item edit text box, the overlaid text box itself will allow you to scroll vertically.

Using the class

Simply add the control to your toolbox. Now use it just as you  would be using a regular list box. Try entering long strings. And run the program. Try editing the strings by either pressing the F2 key or by right clicking on an item. See how the alert message box pops up when you try to modify an item string to a null string. I added this feature because in the project where I'll be using this, null strings are strictly forbidden. Perhaps you might want to allow null strings, if so feel free to comment out the relevant code in the source code.

Technical details

Well obviously the DrawMode is set to DrawMode.OwnerDrawVariable. We need to figure out the height required per item. This is how we do it it in the OnMeasureItem override,

//...


string s = Items[e.Index].ToString();
SizeF sf = e.Graphics.MeasureString(s,Font,Width);
int htex = (e.Index==0) ? 15 : 10;
e.ItemHeight = (int)sf.Height + htex;			
e.ItemWidth = Width;

//...

Now we need to actually draw the  text as this is an owner drawn list box. We override OnDrawItem as shown below.

protected override void OnDrawItem(DrawItemEventArgs e)
{
    //...


    /*chk if list box has any items*/
    if(e.Index > -1)
    {
        string s = Items[e.Index].ToString();                           

        /*Normal items*/
        if((e.State & DrawItemState.Focus)==0)
        {
            e.Graphics.FillRectangle(
                new SolidBrush(SystemColors.Window),
                e.Bounds);
            e.Graphics.DrawString(s,Font,
                new SolidBrush(SystemColors.WindowText),
                e.Bounds);              
            e.Graphics.DrawRectangle(
                new Pen(SystemColors.Highlight),e.Bounds);              
        }
        else /*Selected item, needs highlighting*/
        {
            e.Graphics.FillRectangle(
                new SolidBrush(SystemColors.Highlight),
                e.Bounds);
            e.Graphics.DrawString(s,Font,
                new SolidBrush(SystemColors.HighlightText),
                e.Bounds);
        }
    }
}

Well, so far so good. Now for the in-place editing, what we do is to derive a class from TextBox and add it to our list box. And we handle the OnMouseUp method to check if the user has right clicked an item.

protected override void OnMouseUp(
    System.Windows.Forms.MouseEventArgs e)
{
    //...



        /* Is it a right mouse clk? */
        if(e.Button == MouseButtons.Right)
        {

            string s = Items[index].ToString();
            Rectangle rect = GetItemRectangle(index);

            //overlay the text box right over

            //the list box item to be edited

            tbox.Location = new Point(rect.X,rect.Y);
            tbox.Size = new Size(rect.Width,rect.Height);
            tbox.Text = s;              
            tbox.index = index;
            tbox.SelectAll();
            tbox.Show();
            tbox.Focus();
        }

    //...

}

And similarly we handle OnKeyDown for checking whether the user has pressed the F2 key.

protected override void OnKeyDown(KeyEventArgs e)
{
    if(e.KeyData == Keys.F2)
    {
        //...


            string s = Items[index].ToString();
            Rectangle rect = GetItemRectangle(index);

            tbox.Location = new Point(rect.X,rect.Y);
            tbox.Size = new Size(rect.Width,rect.Height);               
            
        //...

    }
    
    //...

}

In the TextBox derived class we override both OnLostFocus and OnKeyPress (check for Enter key) and make checks to ensure that the user will not enter a null string. The source code can be examined for the finer details, but basically that's all the class does and this class is a private inner class of the MultiLineListBox class. I also check for the Escape key in the OnKeyPress handler to allow the user to cancel a modification.

Conclusion

I hope to get your feedback - both good and bad. I'd also like to know whether anyone actually found this useful enough to use in an application. Or whether the class can be improved in any particular manner. As for myself I spent the whole day dealing with various kinds of issues I ran into, mostly due to my custom control coding inexperience rather than due to any great difficulty in what I was attempting.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Nishant Sivakumar


Member
Nish is a real nice guy living in Atlanta, who has been coding since 1990, when he was 13 years old. Originally from sunny Trivandrum in India, he recently moved to Atlanta from Toronto and is a little sad that he won't be able to play in snow anymore.

Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com

Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.

Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.

Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.
Location: United States United States

Other popular Combo & List Boxes articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 50 (Total in Forum: 50) (Refresh)FirstPrevNext
GeneralNish PinmemberWillie Hall10:52 24 Jun '09  
GeneralAdded support for "SetSelected" [modified] PinmemberMember 425856012:15 19 Jan '09  
GeneraldataSource Pinmemberbfis1081378:03 29 Jul '08  
GeneralShweet!!!! Pinmembershahbaznihal9:07 11 Jul '08  
GeneralNice work! but one problem when editing Pinmemberseanzcan10:00 1 Jun '08  
GeneralGet Text Pinmemberg8kpr0015:42 7 Dec '06  
GeneralThis is nice PinmemberKrenshau7518:16 5 Nov '06  
GeneralSlight Update to allow for Multi-Select PinmemberMoxie9:09 13 Oct '06  
GeneralRe: Slight Update to allow for Multi-Select PinmemberMoxie9:11 13 Oct '06  
GeneralCool PinmemberPaul Conrad8:22 8 Jul '06  
GeneralGreat Job DUDE [modified] PinmemberPrashanth Kota12:49 11 Jun '06  
QuestionProblem Adding a User defined Index ID to the Listbox Pinmemberkkungli15:22 26 May '06  
Generalgood work, but problem with item size Pinmembersandrokan6:42 25 May '06  
GeneralCF version? Pinmembernaveed14:19 2 Feb '06  
GeneralNice "sample" text in the image Pinmembermalharone11:57 17 Oct '05  
Generalproblem with OnMeasureItem Pinmembervomax14:33 13 Oct '05  
GeneralThanks Nish PinmemberMatt Philmon10:10 4 Apr '05  
GeneralDataSource Pinsussandrija1115:44 22 Jul '04  
GeneralNot able to add the MultilineListBox PinmemberBinalShah10:04 30 Apr '04  
GeneralRe: Not able to add the MultilineListBox Pinmemberdef10241:06 22 Feb '05  
GeneralRichText PinmemberuTILLIty4:30 21 Jan '04  
GeneralRight-Click Menu in list box PinsussSawan00716:40 29 Nov '03  
GeneralRight-Click Menu in list box PinmemberSawan00716:40 29 Nov '03  
Generalhelllo Pinmembersirang20:19 20 Jun '03  
GeneralCan I append the multiline item with blanks? PinmemberShailaja3:21 8 Apr '03  

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

PermaLink | Privacy | Terms of Use
Last Updated: 4 Aug 2002
Editor: Chris Maunder
Copyright 2002 by Nishant Sivakumar
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project