C. Student C. Student - 2 months ago 10
C# Question

Trying to get the list box to change the background color of the form c#

Okay, so i'm trying to get the items in the list box to change the background color of the form. So, if the user were to click the option yellow, it would automatically change the background color of the form. This is the code that I have written.

private void listbox_Click(object sender, EventArgs e)
{
string selected_color;
if (listbox.SelectedIndex != -1)
{
colorSel = colorsLstBx.SelectedIndex.ToString();
switch (selected_color)
{
case "Yellow":
this.BackColor = Color.Yellow;
break;
//othercolors
}
}
}

Answer

Your code has several flaws. In your code you use two different listboxes: listbox & colorsLstBx. Next you convert the selectedIndex to a string which is then "0", "1", etc. and not "Yellow", "Red" etc.

This works for me:

 private void listBox_Click(object sender, EventArgs e)
    {
       if (listBox.SelectedIndex != -1)
        {
            var colorSel = listBox.SelectedItem.ToString();
            switch (colorSel)
            {
                case "Yellow":
                    this.BackColor = Color.Yellow;
                    break;
                //othercolors
            }
        }
    }

enter image description here

Comments