Learn ASP.NET Web Forms and ASP.NET MVC. Intensive courses for professional developers. Conducted by Bipin Joshi in Thane. Read more details here.

Using Radio Buttons To Select DataGrid Row

Introduction

Radio Buttons are used to select an option from a set of options. From a given set of radio buttons you can select one and only one radio button. This feature can be used to select a row from DataGrid. This article tells you how to do that.

Why RadioButton web control can not be used directly?

DataGrid allows you to put any controls inside a template column. You must be thinking that on the same line one can add RadioButtons web control as well. However, there is a catch. Radio buttons behave as a single group based on their GroupName property. When put inside DataGrid, DataGrid acts as their naming container and generates a unique name for each radio button. This causes each radio button to operate independently of others. The way out is to capture certain events of DataGrid and emit HTML mark up that represents radio button with appropriate name set.

Solving the problem

In order to solve the problem mentioned above, create a template column and put a Label web control in it. In the ItemDataBound event of the DataGrid write code that emits <INPUT> element with type as Radio and set its Name attribute. This will display the grid with radio buttons in the column. You can select any one of the radio button at a time.

Retrieving selected radio button value

Our task is still not complete. How do we retrieve the selected radio button? Since we are not using RadioButton web control, we can not directly refer it as usual. Request.Form collection comes to rescue here. You can directly retrieve the selected radio button using this collection as in traditional ASP.

Maintaining state

Since we are not using RadioButton web control, we can not avail automatic state management feature of ASP.NET. We have to do the task of maintaining state on our own. This way when the form is loaded in the browser after post back, the previously selected radio button is shown as selected again. This is done by iterating through the items of DataGrid and adding "checked" to the <INPUT> tag.

Sample Application

The sample source code provided with article illustrates above technique.

Bipin Joshi is the founder of BinaryIntellect Consulting and conducts professional training programs on ASP.NET in Thane. He is a published author and has authored or co-authored books for Apress and Wrox press. To know more about him click here. To know more about his training programs go here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Associated Links
Download Source Code

Tags : ASP.NET Web Forms Server Controls Data Controls
Posted On : 12 Oct 2002
Current Rating :
Rate this article :


This page is protected by copyright laws. Copying in any form is strictly prohibited. For Copyright notice and legal terms of use click here.

Protected by Copyscape