C# – ASP.NET C# OnMouseOver Event to Make ListBox Appear and Disappear

asp.netc++listboxonmouseovervisibility

I have a single webform that has a listbox and a button. When the onmousover event fires the listbox will appear; however on page load, the listbox should not be visible. I have the following code (please excuse the background color changes):

Button2.Attributes.Add("onmouseout", 
                       "this.style.backgroundColor='Blue', 
                       ListBox3.style.display ='none'");
Button2.Attributes.Add("onmouseover", 
                       "this.style.backgroundColor='Red',
                       ListBox3.style.display='block'");

This code works when the listbox.visible is set to true. Unfortunately, when the page loads, the listbox is always visible, which is what I want to avoid. When I set the listbox to visible = false, the above code doesn't work. I've messed around with postback and used if statements, such as if (button = red), display=block; however, to no avail. I am stuck at this point. Does anyone know what additional things I need to do to get the above code to work? I am new with ASP.NET, so I don't know if I also have to do something with the html. Also, one interesting point, the backgroundcolor portion of the code works flawlessly.

I really appreciate everyone's help.

Best Solution

When you set Listbox visible="false" in the server-side code, the HTML for the listbox is not rendered and sent to the client. Therefore, you need to ensure that the listbox gets rendered, but is set to not be visible upon page load, either by

  • having an initial CSS style that makes the listbox not visible

or

  • setting it as not visible when the DOM has loaded, using JavaScript on the client.

Also have a look at this Display vs. Visibility article

Related Question