Hello
I am trying to make listbox, the items must be colored and whenever one of its items selected that item changed its color
And if I select it again its color returns back (toggle), but surprisingly that happened when I press the vertical scroll (against my desire)
I want it to become toggle when I select that item using mouse.
I think the index of the wanted item will not be available in mouse click event(mouseclick(object sender, MouseEventArgs e)) .
I will accept the answer even if you add another button or by any other way
thanks
What I have tried:
int[] MARK = new int[10];
ListBox lb = new ListBox();
private void FormLoad(object sender, EventArgs e)
{
for (i = 0; i < 10; i++) str3[i] = "Hello_"+i.ToString();
lb.Items.AddRange(str3);
lb.Location = new System.Drawing.Point(80, 40);
lb.Size = new System.Drawing.Size(160, 80);
lb.DrawMode = DrawMode.OwnerDrawFixed;
lb.DrawItem += new DrawItemEventHandler(MyListBox_DrawItem);
Controls.Add(lb);
}
private void MyListBox_DrawItem(object sender, DrawItemEventArgs e)
{
ListBox lbSender = (ListBox)sender;
if (lbSender == lb && (e.State & DrawItemState.Selected) != DrawItemState.Selected)
{
e.DrawBackground();
string s = lb.Items[e.Index].ToString();
Brush brush = Brushes.Green;
if (MARK[e.Index] == 0) {brush = Brushes.Blue;}
else if (MARK[e.Index] == -1) {brush = Brushes.Red;}
e.Graphics.DrawString(lb.Items[e.Index].ToString(), e.Font, brush, e.Bounds.Location, StringFormat.GenericDefault);
}
else if (lbSender == lb && (e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
e.DrawBackground();
string s;
Brush brush = Brushes.Green;
if (MARK[e.Index] == 0) {brush = Brushes.Red;MARK[e.Index] = -1;}
else if (MARK[e.Index] == -1){brush = Brushes.Blue;MARK[e.Index] = 0;}
s = lb.Items[e.Index].ToString();
e = new DrawItemEventArgs(e.Graphics,
e.Font,
e.Bounds,
e.Index,
e.State ^ DrawItemState.Selected,
e.ForeColor,
Color.Black);
e.Graphics.DrawString(lb.Items[e.Index].ToString(), e.Font, brush, e.Bounds.Location, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
}