When we use the the radio Button inside the gridview or the repeater at that time radiobutton is not working as it’s default behaviour.
Means,Inside the gridview/repeater user able to select more then one option at a time.For which radioButton is not built.
To allow a user to select only one optional at a time.You need to something more then just putting radiobutton control inside the gridview/Reapeter.
In This article I have taken the example of the radiobutton inside the repeater.However,Similar thing can be implement for gridview / DataList.
Step 1:
Drag and drop Radiobutton control inside the Repeater’s item-template. And give the ID and group name same. ( It’s not Mandatory that they both same)
<asp:RadioButton runat=”server” ID=”IdOfRepeter” GroupName=”IdOfRepeter” />
Step 2:
Binding javascript with RadioButton’s onclick Evetn inside the Repeter’s ItemDataBound Event.
protected void RepeterName_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//if control is not Radiobutton retun
if (e.Item.ItemType != ListItemType.Item &&
e.Item.ItemType != ListItemType.AlternatingItem)
return;
//get the reference of the radioButton by id
//“IdOfRepeter” means your Repeter id
RadioButton rdo = (RadioButton)e.Item.FindControl(”IdOfRepeter”);
// Create the javascriot function with paramater value.
//“IdOfRepter”Means group Name
string script = “SetUniqueRadioButton(’IdOfRepter ‘,this)”;
//register javaScript with Radiobutton click Event.
rdo.Attributes.Add(”onclick”, script);
}
Setp 3:
Create javascipt block in head section and add function which we have register with Radiobutton.
<script type=”text/javascript” language=”javascript”>
//<summary>This function will provide used to select the only one radioButton at a time.</summary>
//<param name=’nameregex’>point to name Groupname of RadioButton</param>
//<param name=’current’>point to clicked RadioButton</param>
function SetUniqueRadioButton(nameregex, current)
{
//Get the group name of checkBox
var re = nameregex;
//Looping through the all the control on the page
for(i = 0; i < document.forms[0].elements.length; i++)
{
//get the current control
elm = document.forms[0].elements[i]
//check for the type(if it’s radio button then go inside the loop)
if (elm.type == ‘radio’)
{
//if radiobutton belong to same Groupname
if(re.match(elm.value))
{
//set selected to false for all
elm.checked = false;
}
}
}
//Set currently click Radio Button selected as true.
current.checked = true;
}
</script>