When you put an <select>
element, you put the runat="server"
attribute on the WebControl HtmlSelect that does not support optgroup
.
To get access to the selected option from the server, you have two options
Option 1: Element pure HTML select and the selected value access through Request.Form
. The drawback of this option is that it remains a pretty ugly code (especially to set the selected item from server)
HTML Code:
<select name="CarField">
<option value="">-Seleccione una opción-</option>
<optgroup label="Swedish Cars">
<option value="volvo" <%=SelectedCar == "volvo" ? "selected" : ""%>>Volvo</option>
<option value="saab" <%=SelectedCar == "saab" ? "selected" : ""%>>Saab</option>
</optgroup>
<optgroup label="German Cars">
<option value="mercedes" <%=SelectedCar == "mercedes" ? "selected" : ""%>>Mercedes</option>
<option value="audi" <%=SelectedCar == "audi" ? "selected" : ""%>>Audi</option>
</optgroup>
Code C #
public partial class _Default : Page
{
protected string SelectedCar { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
SelectedCar = Request.Form["CarField"];
Label1.Text = $"El coche seleccionado es: {SelectedCar}";
}
}
Option 2 : Implement a WebControl. In this article (in English) " ADDING GROUPS TO THE ASP.NET DROPDOWNLIST CONTROL "You have an example of implementation. This would be the recommended option, especially to have a cleaner and reusable code.