Introduction
All of us like more color or image in our control, so do I.
In this article, I give each item in the custom ListBox
class an image property.
Note: my article has no source code because it very short and easy.
First: we create 2 classes for GListBox
public class GListBoxItem
{
private string _myText;
private int _myImageIndex;
public string Text
{
get {return _myText;}
set {_myText = value;}
}
public int ImageIndex
{
get {return _myImageIndex;}
set {_myImageIndex = value;}
}
public GListBoxItem(string text, int index)
{
_myText = text;
_myImageIndex = index;
}
public GListBoxItem(string text): this(text,-1){}
public GListBoxItem(): this(""){}
public override string ToString()
{
return _myText;
}
}
public class GListBox : ListBox
{
private ImageList _myImageList;
public ImageList ImageList
{
get {return _myImageList;}
set {_myImageList = value;}
}
public GListBox()
{
this.DrawMode = DrawMode.OwnerDrawFixed;
}
protected override void OnDrawItem(System.Windows.Forms.DrawItemEventArgs e)
{
e.DrawBackground();
e.DrawFocusRectangle();
GListBoxItem item;
Rectangle bounds = e.Bounds;
Size imageSize = _myImageList.ImageSize;
try
{
item = (GListBoxItem) Items[e.Index];
if (item.ImageIndex != -1)
{
imageList.Draw(e.Graphics, bounds.Left,bounds.Top,item.ImageIndex);
e.Graphics.DrawString(item.Text, e.Font, new SolidBrush(e.ForeColor),
bounds.Left+imageSize.Width, bounds.Top);
}
else
{
e.Graphics.DrawString(item.Text, e.Font,new SolidBrush(e.ForeColor),
bounds.Left, bounds.Top);
}
}
catch
{
if (e.Index != -1)
{
e.Graphics.DrawString(Items[e.Index].ToString(),e.Font,
new SolidBrush(e.ForeColor) ,bounds.Left, bounds.Top);
}
else
{
e.Graphics.DrawString(Text,e.Font,new SolidBrush(e.ForeColor),
bounds.Left, bounds.Top);
}
}
base.OnDrawItem(e);
}
}
After that, in order to use our code, we could do:
GListBox lb = new GListBox();
lb.ImageList = imageList;
lb.Items.Add( new GListBoxItem("Image 1",0));
lb.Items.Add( new GListBoxItem("Image 2",1));
lb.Items.Add( new GListBoxItem("Image 3",2));
That's all and thanks for reading.