Thursday 19 May 2011

Windows App : Set an image in ListViewSubItem

For background details about the error, see this link...
http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/229d8b6e-f167-48ee-aa2e-931e6ee7eb2b/


If you really do wanna set an image in ListVewSubItem, it's a bit tricky. You've to handle the following events of a list view
DrawSubItem
DrawColumnHeader


Now implement DrawColumnHeader

private void ListViewDrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
        {
            e.DrawDefault = true;
        }

And DrawSubItem
private void ListViewDrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
       if (e.ColumnIndex == 1)
       {
          ((TriboldExtendedListView) sender).FullRowSelect = true;

if (e.ColumnIndex == 1)
{
//This allows window to draw background otherwise your column would be blank in //anyway
e.DrawBackground();

//Draw you graphics here
e.Graphics.DrawImage(img, new System.Drawing.RectangleF(e.Item.Position.X + Columns[0].Width - 10, e.Item.Position.Y, img.Width*(fScale), img.Height*(fScale)));

//Draw your text here
e.DrawText(TextFormatFlags.Left);



//This is something really important if you want to set the highlighted color //(windows blue) to the ListViewSubItem
e.Item.UseItemStyleForSubItems = false;
if (e.Item.Selected)
{

 e.Item.SubItems[1].BackColor = System.Drawing.Color.FromArgb(51, 153, 255);
 e.Item.SubItems[1].ForeColor = System.Drawing.Color.FromArgb(255, 255, 255);
}
else
{
 e.Item.SubItems[1].BackColor = System.Drawing.Color.FromArgb(229, 229, 229);
 e.Item.SubItems[1].ForeColor = System.Drawing.Color.FromArgb(0, 0, 0);
}

}}
}

If you need any information about, feel free to post.