If you try the following, it should set the
visible text of the dropdown control in question, right?
listControl.Text = "4 Year College";
Well, unfortunately, no! The "Text" property is named that way for consistency across all ASP.NET controls and refers to the form value that is passed to the server when the page is submitted. So unfortunately for me, the "Text" property silently rejected my attempt to set it and the page did not work.
You may be asking yourself why I am trying to set the visible text and not the
value of the control. The reason is that the application I'm working on receives the displayed text from a web service and not the value that is passed in the form variables. Why not create a dictionary, look up the the text string in the dictionary, and pass
that to the control?
The answer? I already have a dictionary. It's called the SELECT control itself. The generated HTML for my control is, say, the following:
This control is essentially a dictionary of key-value pairs: the key is the value attribute of the option tag, and the value is the visible text that is displayed for the given item in the dropdown list. So in the spirit of Don't Repeat Yourself (DRY), I wrote a extension function to allow me to set not just the value but also the text. I give you ListControlExtensions.cs:
Here's a typical usage. In this particular scenario, my data should be scrubbed, but if not I log a warning: