Un-Select a Radio-Button by clicking on it


The situation is kind of odd however, not uncommon, atleast, I would think so. We have got a Radio Button inside each row of a GridView. As per the requirement, user should be able to select only 1 radio button at a time. This has been achieved with javascript. More details can be found here. Now selecting radio button indicates the selection for that row of the gridview. Similarly, there should be an option for dis-selecting the radio button by clicking on the selected radio button (much like the checkboxes). However, this is against the normal behaviour of the radio button, and obviously there was no simple way of doing it. So I decided to put a check on the OnClick property of the Radio Button. The check was like this

if (rdBtn.checked == true {
	rdBtn.checked = false;

However, because of this, I was not able to select the Radio Button in the first place. Unlike, checkbox, once checked, a radio button will always return true when it is checked and my script was simply clearing the checked state thereby, not letting me select any option.


After doing a bit of R&D I realized that instead of making things complicated, I should put a simple check, & instead of relying on the checked property of the radio button I will check the id of the current selected radio button. If the current radio button’s id matches with that of the hiddenField value, I will simply clear the check of that radio button

<script language="javascript" type="text/javascript">
	function SelectSingleRadiobutton(rdbtnid) {
		var hd = document.getElementById('hdnFld');
		var rest = false;
		var rdBtn = document.getElementById(rdbtnid);
		var rdBtnList = document.getElementsByTagName("input");
		for (i = 0; i < rdBtnList.length; i++) {
			if (rdBtnList[i].type == "radio") {
				if (rdBtnList[i].id != rdBtn.id) {
					rdBtnList[i].checked = false;
				else if (hd.value == rdBtnList[i].id) {
					rdBtnList[i].checked = false;
					rest = true;
		hd.value = (rest) ? "" : rdbtnid;

Inside the GridView’s ItemTemplate I have called the above script for the OnClick event of the Radio Button

		<asp:RadioButton ID="rdbOptions" runat="server" OnClick="javascript:SelectSingleRadiobutton(this.id)" />
	<ItemStyle HorizontalAlign="Center" />

That’s it …

Place a GridView in the Center of a DIV

To place a GridView in the center of a div one thing that we do is to use the property text-align:center. However as per the current css, it won’t work. What we need to do is to use the code margin-left: auto; margin-right: auto;. Either put that in the css Class of the GridView or you can directly put it inside the Grid like the following

<asp:GridView ID="grdExamSchedules" runat="server" ForeColor="#333333" 
              style="margin-left:auto; margin-right:auto" >

Thanks …