Monday, November 3, 2008

Single RadioButton Selection in GridView

During my development work i came across a problem when i have to insert the RadioButton control in the grid view control and have to select the only one radio button at a time, i have use the radio button property groupName but it didn't work, So after search on net i came to know what the problem is the link which i have read and i came to know that the radio button groupName property is not working is Dan's Archive , where he mention that "Each row in a GridView is its own naming container so the controls' names don't collide. However, RadioButtons do not support spanning multiple naming containers and having their groupname attribute still work correctly. We will be looking at solving the RadioButton GroupName/multiple naming container issue in future versions of the product." he also give solution to the problem , but the solution which i will present here is different from that solution.

here is the javascript code

function SelectSingleRadioButton(currentRowRadioButtonID)
{
var radioButton = document.getElementById(currentRowRadioButtonID);

var targetBaseControl = document.getElementById('<%= grdvGridViewName.ClientID %>');
var gridViewInputControls = targetBaseControl.getElementsByTagName("input");
for(var intCounter = 0; intCounter < gridViewInputControls.length; ++intCounter)
{
if(gridViewInputControls[intCounter].type == 'radio')
gridViewInputControls[intCounter].checked = false;
}

radioButton.checked = true;
}


at the end on the server side you have to put the following code


protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
RadioButton rdbCurrentRadioButton = (RadioButton)e.Row.FindControl("RadioButtonName");

e.Row.Attributes.Add("onclick", "SelectSingleRadioButton('" + rdbCurrentRadioButton.ClientID + "');");
}
}

and you will select one radioButton at a time
Happy Propgramming :)

No comments: