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. namespace ListView_DisableSpecificItem
  11. {
  12. public partial class Form1 : Form
  13. {
  14. public Form1()
  15. {
  16. InitializeComponent();
  17. }
  18. SchoolManagementEntities objSchoolManagementEntities = new SchoolManagementEntities();
  19. private void Form1_Load(object sender, EventArgs e)
  20. {
  21. var query = from r in objSchoolManagementEntities.Students select r;
  22. foreach (var p in query)
  23. {
  24. ListViewItem item = new ListViewItem();
  25. item.Text = p.FirstName;
  26. if (item.Text == "Andy")
  27. {
  28. item.BackColor = System.Drawing.Color.Gray;
  29. }
  30. listView1.Items.Add(item);
  31. }
  32. }
  33. private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
  34. {
  35. if (e.IsSelected && e.Item.Text == "Andy")
  36. {
  37. e.Item.Selected = false;
  38. }
  39. }
  40. }
  41. }

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!