There are a few examples on the Net. One of them is in documentation of the DrawText method of the ListViewItem:
http://msdn.microsoft.com/en-us/library/989zcatz.aspx[
^]
I found that the DrawText() method does not position the text properly, no matter what flags I passed it. So I used the DrawString instead (which still didn't position it perfectly, but at least there's more control over e.DrawString). You are probably showing an icon in the first column, so you will have to use the e.Graphics to draw the image.
On a side note. ListView is not a good control to display data. You'll be sorry you ever chose it if you ever need to customize some more. Consider a DataGridView instead.
public partial class Form1 : Form
{
private ColumnHeader _iconHeader;
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
listUsers1.View = View.Details;
listUsers1.FullRowSelect = true;
_iconHeader = listUsers1.Columns.Add("Icon", 35, HorizontalAlignment.Left);
listUsers1.Columns.Add("Name", 200, HorizontalAlignment.Left);
listUsers1.Items.Add(new ListViewItem(new[] { "def", "def" }));
listUsers1.Items.Add(new ListViewItem(new[] { "abc2", "def" }));
listUsers1.Items.Add(new ListViewItem(new[] { "abc3", "def" }));
listUsers1.Items.Add(new ListViewItem(new[] { "abc4", "def" }));
listUsers1.OwnerDraw = true;
listUsers1.DrawItem += new DrawListViewItemEventHandler(listUsers1_DrawItem);
listUsers1.DrawSubItem += new DrawListViewSubItemEventHandler(listUsers1_DrawSubItem);
listUsers1.DrawColumnHeader += new DrawListViewColumnHeaderEventHandler(listUsers1_DrawColumnHeader);
}
void listUsers1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
ListViewItemStates selectedState = ListViewItemStates.Selected | ListViewItemStates.Focused;
if (selectedState == (e.State & selectedState))
{
e.DrawBackground();
e.DrawText();
}
else
{
e.DrawDefault = true;
}
}
void listUsers1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
e.DrawDefault = true;
}
void listUsers1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
if (e.ColumnIndex == listUsers1.Columns.IndexOf(_iconHeader)
&& (e.ItemState & ListViewItemStates.Focused) == ListViewItemStates.Focused)
{
e.DrawBackground();
using (StringFormat sf = new StringFormat())
{
sf.Alignment = StringAlignment.Near;
sf.LineAlignment = StringAlignment.Center;
e.Graphics.DrawString(e.SubItem.Text, listUsers1.Font, Brushes.Black, e.Bounds, sf);
}
}
else
{
e.DrawDefault = true;
}
}
}