How To Disable Selected Item In List Box

后端 未结 3 532
小蘑菇
小蘑菇 2020-12-19 03:49

I have a ListBox in my WinForms application and I want to disable some items on that list, for example if I right click on an item , it gets disabl

3条回答
  •  不思量自难忘°
    2020-12-19 04:17

    There is no native Disable/Enable items in ListBox. However you can do some tricks.

    First you need to define you own class for item which will have Enabled property.

    Then you need to subscribe to MouseDown event and check which (righ or left) button was clicked. And based on x,y position get the item that was clicked. Then you will set the Enabled property to True/False. Below are some examples :

    Your custom class

        public class Item
        {
            public Item()
            {
                // Enabled by default
                Enabled = true;
            }
            public bool Enabled { get; set; }
            public string Value { get; set; }
            public override string ToString()
            {
                return Value;
            } 
        }
    

    The MouseDown event

    private void listBox1_MouseDown(object sender, MouseEventArgs e)
    {
    
        var item = (Item)listBox1.Items[listBox1.IndexFromPoint(e.X, e.Y)];
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            item.Enabled = false;
        }
        else
        {
            item.Enabled = true;
    
        }
    }
    

提交回复
热议问题