Introduction
Very often, it's required to have a radio button column in a DataGrid
. A grid listing of user details along with a radio button, would be a typical example. The requirement may be to select a user from the list of users. On changing the user in the grid, the previous selection should be cancelled.
Achieving this at the client side will reduce the communication between the server and the client and will thereby reduce the network traffic.
The following example will explain how to achieve this.
Section 1 : ASPX code
The user details are fetched from the database and filled to a DataSet
. The DataSet
is made the data source for the DataGrid
.
<form id="frmSecurity" method="post" runat="server">
<asp:datagrid id="dgrUserAcctList" runat="server" GridLines="Horizontal" >
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:RadioButton id="radUserAccount" runat="server" Text=''></asp:RadioButton>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn Visible = "False" DataField="USER_ID"></asp:BoundColumn>
<asp:BoundColumn DataField="USER_NAME" HeaderText="User� </asp:BoundColumn>
<asp:BoundColumn DataField="USER_DEPT" HeaderText="Deparatment "></asp:BoundColumn>
<asp:BoundColumn DataField="USER_ROLE" HeaderText="Role"></asp:BoundColumn>
</Columns>
</asp:datagrid>
</form>
Section 2 : Code behind (ASPX.vb)
At the code-behind the ItemDataBound
event of the DataGrid
is implemented as below:
Private sub dgrUserAcctList _ItemDataBound(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) _
Handles dgrUserAcctList.ItemDataBound
Try
If e.Item.ItemIndex > -1 Then
Dim strSelRadio As String = _
e.Item.Cells(0).FindControl("radUserAccount ").ClientID()
CType(e.Item.FindControl("radUserAccount "), _
RadioButton).Attributes.Add("onClick", _
"fnCheckSel('" + strSelRadio + "')")
End If
Catch ex As Exception
//Exception handling
End Try
End Sub
Section 3: JavaScript code
Now the client side validation using JavaScript can be written as:
function fnCheckSel(intObjId)
{
var strSceTypeId;
strSceTypeId = intObjId + "1"
for (var i=1; i<document.forms(0).length; i++)
{ if(document.forms(0).elements[i].id )
{ if(document.forms(0).elements[i].id.indexOf("radUserAccount")!=-1)
{if (document.forms(0).elements[i].id.indexOf("radUserAccount1")==-1)
{document.forms(0).elements[i].checked=false
}}}}
document.getElementById(intObjId).checked=true
}
In the same manner, if the selection of atleast one user is mandatory, the validation at the form submission can be done using the function below:
function fnCheckVal(intObjId)
{
var found_it ;
for (var i=1; i<document.forms(0).length; i++)
{ if(document.forms(0).elements[i].id )
{ if(document.forms(0).elements[i].id.indexOf("radUserAccount")!=-1)
{if (document.forms(0).elements[i].checked)
{
found_it = true;
break;
}}}}
if(!found_it)
{alert("Select an Account");
return false;
}
else
{return true;
}
}
That's all.