Tuesday, May 13, 2014

Get HTML Drop Down List value in code behind C#

Few days ago I stuck into a problem , I need to get the value of from a HTML drop down list in my c# code behind page. So I started searching and found the solution.  Very simple solution indeed. Just a single line code to end the problem.

Suppose the drop down list code is


<select name="cars">
  <option value="volvo">Volvo XC90</option>
  <option value="saab">Saab 95</option>
  <option value="mercedes">Mercedes SLK</option>
  <option value="audi">Audi TT</option>
</select>

And a ASP button to get the value..


<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

Now on the C# page write the bellow code.


var car = Request["cars"];
Response.Write(car.ToString());

If you are using ASP Drop Down List then the code will be little bit different.


<asp:DropDownList ID="DropDownList1" runat="server">
   <asp:ListItem>Item1</asp:ListItem>
   <asp:ListItem>Item2</asp:ListItem>
   <asp:ListItem>Item3</asp:ListItem>
</asp:DropDownList>

And on button click..


Response.Write(DropDownList1.SelectedValue.ToString());
Response.Write(DropDownList1.SelectedItem.Text.ToString());

Now enjoy the code..

0 comments:

Post a Comment

Popular Posts

Pageviews