RadioButton inside GridView, How to get it work as normal.
As we all know, RadioButton control used in a situation when
you want end-users to select only one option at a time from
group of options.
Did you tried before to drag a RadioButton control inside a Gridivew templatefield, and then you attempt to select these RadioButtons , you will notice that the behavior of RadioButton control will be changed and it will work just like the behavior of checkbox control! the user will be able to select more than one radiobutton in the grid!
O.k you can use html radiobutton element instead of server radiobutton control in the templatefield, this will do the trick and the behavior will get back again, but what if you want to do some event in codebeind and collect the selected Radiobutton?! this time you need to add the run at server attribute to the html element to be able to see it in the codebehind, in that case, the behavoir will be changed again and the user can select more than one option from the radio buttons.
So what is the solution for that ?
In simplest scenario, when the situation is only radio button and text beside it, you can use the RadioButtonList control instead, but if the form gets to be more complex and you need to display other controls beside the radiobutton, then (gridview,repeater,datalist) should be your choice.
the below code will help you to accomplish that.
<script
type="text/javascript"
language="javascript">
function
fnCheckUnCheck(objId)
{
var grd =
document.getElementById("<%= GridView1.ClientID %>");
//Collect A
var rdoArray =
grd.getElementsByTagName("input");
for(i=0;i<=rdoArray.length-1;i++)
{
if(rdoArray[i].type ==
'radio')
{
if(rdoArray[i].id !=
objId)
{
rdoArray[i].checked =
false;
}
}
}
}
</script>
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="false"
>
<Columns>
<asp:TemplateField
HeaderText="Select/UnSelect">
<ItemTemplate
>
<input
id="grdRdo"
name="grdRdo"
type="radio"
runat="server"
onclick="fnCheckUnCheck(this.id);"
/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField
DataField="User_Name"
HeaderText="Name"
/>
<asp:BoundField
DataField="User_Department"
HeaderText="Dep"
/>
</Columns>
</asp:GridView>
Protected
Sub Button1_Click(ByVal
sender As
Object,
ByVal e
As System.EventArgs)
For
Each grdRow
As GridViewRow
In GridView1.Rows
Dim htmlRdo
As
New
HtmlInputRadioButton
htmlRdo =
DirectCast(grdRow.FindControl("grdRdo"), HtmlInputRadioButton)
If htmlRdo.Checked
Then
' Do Something
Else
'Do something else
End
If
Next
End Sub
I hope someone will found this very helpful :)
~ Abdulla AbdelHaq