I have the following HTML source
<form name="Register1" action="Register.aspx" id="registerform" method="post"
runat="server" style="margin-top: 15px;">
<input type="radio" name="Gender" value="male" />male
<input type="radio" name="Gender" value="female" />female
</form>
My question is how can I get the selected value to variable in the c# page?
I tried this :
Gender = Request.Form["Gender"].ToString();
But it didn't work...
To start with you will need the form posted the Form collection won't have anything on the page load, so suppose you have a button and you click to submit the form then in the click event handler you can get the selected value with the code you have tried.
I guess the collection is null hence the NullReference exception when you access it.
It is better to access it like
place your code like this:
Note that
Request.Form["Gender"]
will be null if none of the RadioButtons are selected.see the markup below
for both the buttons i.e
input type="submit"
and usualasp:button
,Request.Form["Gender"]
is going to have some value uponPostBack
, provided, either of the RadioButtons is selected.And yes, upon
PostBack
only, i.e. when you hit either of the buttons and not on first load.Use a
RadioButtonList
and get the value with
if you are working with asp.net make sure that HTML control name by Request.Form contains these ct100$ with the name or id through which you are assessing. check the below example.