In this article I will explain how to get the selected Text of HTML Select DropDownList in ASP.Net Code Behind (Server Side) using C# and VB.Net.
There are two ways we can access the HTML Select DropDownList selected Text in ASP.Net Code Behind (Server Side)
1. Using Request Form collection and name property.
2. Using runat = “server” property.
Using Request Form collection and name property
The HTML Select DropDownList does not send its selected Text through Request.Form collection and hence we need to make use of Hidden Field and save the selected Text in the Hidden Field using JavaScript whenever the HTML Select DropDownList is changed.
Select Fruit:
<select id="ddlFruits" name="Fruit" onchange="SetSelectedText(this)">
<option value=""></option>
<option value="1">Apple</option>
<option value="2">Mango</option>
<option value="3">Orange</option>
</select>
<input type="hidden" id = "hfFruitName" name="FruitName" />
<script type = "text/javascript">
function SetSelectedText(ddlFruits) {
var selectedText = ddlFruits.options[ddlFruits.selectedIndex].innerHTML;
document.getElementById("hfFruitName").value = selectedText;
}
</script>
<asp:Button Text="Submit" runat="server" OnClick="Submit" />
Now inside the Button click event handler, the selected Text of the HTML Select DropDownList is fetched from Request.Form using the Name of the Hidden Field.
C#
protected void Submit(object sender, EventArgs e)
{
string fruitName = Request.Form["FruitName"];
}
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
Dim fruitName As String = Request.Form("FruitName")
End Sub
Using runat = “server” property
Following is an HTML Select DropDownList with runat=”server” property.
Select Color:
<select id="ddlColors" runat="server">
<option value=""></option>
<option value="R">Red</option>
<option value="Y">Yellow</option>
<option value="O">Orange</option>
</select>
<br />
<br />
<asp:Button Text="Submit" runat="server" OnClick="Submit" />
Inside the Button click event handler, the selected Text of the HTML Select DropDownList is fetched from its Items collection using the SelectedIndex property.
C#
protected void Submit(object sender, EventArgs e)
{
string colorName = ddlColors.Items[ddlColors.SelectedIndex].Text;
}
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
Dim colorName As String = ddlColors.Items(ddlColors.SelectedIndex).Text
End Sub
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads
Download Code