SYSK 109: Is it possible to change the ForeColor of a SubItem in a ListView?


The other day I came across the question above at http://www.codecomments.com/archive293-2004-7-244806.html, which did not provide the way to accomplish the desired effect.  The answer is – yes, you can.  Here is how you might go above doing it in .NET 2.0 (key lines of code in bold):


 


public class Employee


{


    private string _name;


    private int _id;


    private string _department;


 


    public Employee(string name, int id, string department)


    {


        _name = name;


        _id = id;


        _department = department;


    }


 


    public string Name


    {


        get { return _name; }


    }


 


    public int ID


    {


        get { return _id; }


    }


 


    public string Department


    {


        get { return _department; }


    }


 


    public string[] Data


    {


        get { return new string[] { _name, _id.ToString(), _department }; }


    }


}


 


 


public partial class Form1 : Form


{


    public Form1()


    {


        InitializeComponent();


    }


 


 


    private void Form1_Load(object sender, EventArgs e)


    {


    Employee e1 = new Employee(“Irena Kennedy”, 12345, “IT”);


    Employee e2 = new Employee(“Mike Smith”, 23456, “Sales”);                         


 


    this.listView1.Columns.Add(“Name”);


    this.listView1.Columns.Add(“ID”);


    this.listView1.Columns.Add(“Department”);


 


    this.listView1.View = View.Details;


    this.listView1.Items.Add(new ListViewItem(e1.Data));


    this.listView1.Items.Add(new ListViewItem(e2.Data));


 


    this.listView1.OwnerDraw = true;


    this.listView1.DrawItem += new DrawListViewItemEventHandler(listView1_DrawItem);


    this.listView1.DrawColumnHeader += new DrawListViewColumnHeaderEventHandler(listView1_DrawColumnHeader);


    this.listView1.DrawSubItem += new DrawListViewSubItemEventHandler(listView1_DrawSubItem);


    }


 


    private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)


    {


        e.DrawDefault = false;


    }


 


    private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)


    {


        e.DrawDefault = true;


    }


 


    private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)


    {


        if (e.ColumnIndex == 2)


        {


            if (e.SubItem.Text == “IT”)


                e.SubItem.ForeColor = Color.Red;                   


        }           


    }


}


 


 

Comments (0)