Using Radio Buttons To Select DataGrid Row
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.
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.
The sample source code provided with article illustrates above technique.
Posted On : 12 October 2002
is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a meditation teacher and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his ASP.NET online courses go here
. More details about his Ajapa Japa and Shambhavi Mudra online course are available here