Reputation: 307
I would need a combobox for an ASP.NET site. So the control needs to:
1) - offer several options to be picked up via a dropdown list
2) - let the user write a string that is not present into the dropdown list.
This combobox control already exists (and works fine) in C# for windows applications. But into ASP.NET default controls, there are no such comboboxes. There is just a dropdown list (1) and a textbox (2). The dropdown list does not let you set a My_DropDownList.Text with a string that does not belong to the control's ItemList.
I googled a bit, tested a few custom controls that did not work as I expected. Then I found out about AjaxControlToolkit. It is supposed to offer the exact ComboBox that I need for ASP.Net.
I installed the package, added an ajax ScriptManager as pre-requested and then added the ComboBox. It looks that you can change the My_ComboBox.Text with a new value, but this new value has to belong to the control's ListItem. Otherwise I get the error: "... has a SelectedValue which is invalid because it does not exist in the list of items"
Did I miss anything? My understanding was that we were supposed to be able to set any value into the combobox (as for the default C# combobox provided by VS for win applications).
Alternatively, do you know about any other controls that that I could add to avoid this problem?
Of course, I would have the possibility to do something like:
My_ComboBox.Add(new ListItem("my_String");
My_ComboBox.Text = "my_String";
But I am pretty sure you ll offer me more elegant solutions.
Thx in advance.
Upvotes: 2
Views: 1738
Reputation: 172330
Your mental model of a ComboBox might be "a TextBox with a helpful auto-complete list". However, that's not what the AjaxControlToolkit ComboBox is: Rather, it's a Dropdown which automatically adds new items that are entered by the user.
Thus, from a code perspective, it behaves more like a Dropdown rather than like a TextBox. Your understanding is correct: To set the text to a previously unknown entry, you need to add it to the list first. If the text is entered by the user, this is done automatically.
If your use case would rather need "a TextBox with a helpful auto-complete list", I'd stop searching for a ComboBox and start investingating auto-complete text boxes instead.
Upvotes: 2