How to Disable and Grey Out Specific ListViewItem

Introduction

In this article we will see how to disable and grey out any specific listviewitem based on condition.

Step 1: Create windows forms application

Form.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9. using System.Windows.Forms;  
  10.   
  11. namespace ListView_DisableSpecificItem  
  12. {  
  13.     public partial class Form1 : Form  
  14.     {  
  15.         public Form1()  
  16.         {  
  17.             InitializeComponent();  
  18.         }  
  19.   
  20.         SchoolManagementEntities objSchoolManagementEntities = new SchoolManagementEntities();  
  21.         private void Form1_Load(object sender, EventArgs e)  
  22.         {  
  23.             var query = from r in objSchoolManagementEntities.Students select r;  
  24.   
  25.   
  26.   
  27.             foreach (var p in query)  
  28.             {  
  29.                 ListViewItem item = new ListViewItem();  
  30.   
  31.                 item.Text = p.FirstName;  
  32.   
  33.                 if (item.Text == "Andy")  
  34.                 {  
  35.                     item.BackColor = System.Drawing.Color.Gray;  
  36.                 }  
  37.   
  38.                 listView1.Items.Add(item);  
  39.             }  
  40.        }  
  41.   
  42.         private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)  
  43.         {  
  44.             if (e.IsSelected && e.Item.Text == "Andy")  
  45.             {  
  46.                 e.Item.Selected = false;  
  47.             }  
  48.         }  
  49.     }  
  50. }  

Output of the application looks like this

Summary

In this blog we have seen how we can disable any specific ListViewItem based on condition. Happy coding!

Ebook Download
View all
Learn
View all
MVC Corporation is consulting and IT services based company.