Monday, July 19, 2010

How to make only one radio button selectable in Datalist?

Radio Button Control in ASP.net Datalist/Repeater


How to   make only one radio button selectable in Datalist?





In   your ASPX or ASCX add the following piece of Javascript:

<script language="javascript" type="text/javascript">

function SetUniqueRadioButton(nameregex, current)

{

re = new RegExp(nameregex);

for(i = 0; i < document.forms[0].elements.length; i++)

{

elm = document.forms[0].elements[i]

if (elm.type == 'radio')

{

if (re.test(elm.name))

{

elm.checked = false;

}

}

}

current.checked = true;

}

</script>

Now, in your code behind, and in the ItemDataBound event of your Repeater/Datalist find the Radio Button   control and add an OnClick attribute to call   the Javascript function you just added to your page:

protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)

{

if(e.Item.ItemType==ListItemType.AlternatingItem  || e.Item.ItemType==ListItemType.Item)

{

RadioButton rb=(RadioButton)e.Item.FindControl("rb_plan");

String strFunction = "SetUniqueRadioButton('DataList1.*Package',this)";

rb.Attributes.Add("onclick", strFunction);

}

}

Like :- if your datlist id is "Datalist1" and radibutton groupname id "Package" than the above function would be like -

SetUniqueRadioButton('Datalist1.*Package',this)

No comments:

Post a Comment

Popular Posts