Registration open for May 2018 batches of ASP.NET Core and Angular instructor-led online courses. Conducted by Bipin Joshi on weekends. Register today ! Click here
for more details.
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
Tags : ASP.NET Web Forms Server Controls Data Controls
is a software consultant, trainer, author and yoga mentor having 22+ years of experience in software development. He also conducts online courses
on ASP.NET MVC, ASP.NET Core and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga
to interested individuals. To know more about him click here
Get connected : Twitter Facebook