Pages

How to group radio buttons in gridview

Here I am going to show how to make radio buttons work when they are in gridview column. Radio button's GroupName property does not work because of the way asp.net sets name property of the child controls of a data bound control. I will show how to select exactly one radio button from a gridview column. I will keep it very simple and short.

So when you add a column containing radio button to the gridview it does not work the way you expected.

What you get? What you want?

Consider a following sample markup:
<asp:GridView runat="server" ID="Gridview1" AutoGenerateColumns="false">
     <Columns>
          <asp:TemplateField>
               <ItemTemplate>
                   <asp:RadioButton runat="server" ID="rdb1" onchange="onRadioButtonClick(this)" />
               </ItemTemplate>
          </asp:TemplateField>
          <asp:BoundField HeaderText="FirstName" DataField="FirstName" />
          <asp:BoundField HeaderText="LastName" DataField="LastName" />
     </Columns>
</asp:GridView>
and a JavaScript function:
function onRadioButtonClick(src) {
     // Asp.net radio button gets wrapped inside span whenever any attributes are applied to it, 
     // hence 'src' is actually span and not a radio button itself. So we have to get radio button 
     // from its wrapper (span).
     var srcRdb = src.childNodes[0];

     var gridview = document.getElementById('Gridview1');
     var inputElements = gridview.getElementsByTagName('input');

     // Loop through radio buttons in Gridview
     for (var i = 0; i < inputElements.length; i++) {
         var ele = inputElements[i];
         // Check if input element is radio button
         if (ele.type == 'radio') {
             // Uncheck radio buttons (except srcRdb) which are checked
             if (ele != srcRdb && ele.checked) {
                 ele.checked = false;
                 // There will always be only one checked radio button (other than srcRdb).
                 // So stop looping as soon as that is unchecked.
                 break;
             }
         }
     }
}
I feel, the code comments and the script are enough to understand how it works (yes, it works! :)).

What next?

Let's add another radio button column to the gridview and view the page in browser. Selected radio button gets unchecked when you select another one from second column! Certainly, this is not what you want if there are multiple columns containing radio buttons. Well, there's a simple fix for this, however, note that if you have only one column with radio buttons you are good to go with the script above. The following changes, though they will work for single column too, are required only in case of multiple columns with radio buttons.

The idea is to pass an extra parameter, id of the radio button, to our javascript function and then pick up only those input controls whose id contains the id passed as parameter. For example, in our case, the ids of radio buttons in first columns are set to (by asp.net, after page is rendered) 'Gridview1_rdb1_0' (row 0 col 0), 'Gridview1_rdb1_1' (row 1 col 0), 'Gridview1_rdb1_2' (row 2 col 0) and so on. 'rdb1' is guaranteed to be present in all the rendered IDs as it was set at design time.

Here's the final markup and javascript function for the multiple columns with radio buttons in a gridview:
<asp:GridView runat="server" ID="Gridview1" AutoGenerateColumns="false">
     <Columns>
         <asp:TemplateField>
              <ItemTemplate>
                   <asp:RadioButton runat="server" ID="rdb1" onchange="onRadioButtonClick(this,'rdb1')" />
              </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField>
              <ItemTemplate>
                   <asp:RadioButton runat="server" ID="rdb2" onchange="onRadioButtonClick(this,'rdb2')" />
              </ItemTemplate>
         </asp:TemplateField>
         <asp:BoundField HeaderText="FirstName" DataField="FirstName" />
         <asp:BoundField HeaderText="LastName" DataField="LastName" />
     </Columns>
</asp:GridView>
function onRadioButtonClick(src, arg) {
      // Asp.net radio button gets wrapped inside span whenever any attributes are applied to it, 
      // hence 'src' is actually span and not a radio button itself. So we have to get radio button 
      // from its wrapper (span).
      var srcRdb = src.childNodes[0];

      var gridview = document.getElementById('Gridview1');
      var inputs = gridview.getElementsByTagName('input');

      var inputElements = new Array();
      // Get radio buttons from same column
      for (var i = 0; i < inputs.length; i++) {
          if (inputs[i].id.indexOf(arg) > -1)
              inputElements.push(inputs[i]);
      }

      // Loop through radio buttons in Gridview
      for (var i = 0; i < inputElements.length; i++) {
          var ele = inputElements[i];
          // Check if input element is radio button
          if (ele.type == 'radio') {
              // Uncheck radio buttons (except srcRdb) which are checked
              if (ele != srcRdb && ele.checked) {
                  ele.checked = false;
                  // There will always be only one checked radio button (other than srcRdb).
                  // So stop looping as soon as that is unchecked.
                  break;
              }
          }
      }
}

I have seen number of articles on this which include server side code in C#, whilst respecting all those solutions, I believe there's nothing needed to be done on server side when you can easily do the same at client side (I hate post-backs. :D), also it does not mean I am the only one who showed how to do this with javascript. I am yet to learn javascript and asp.net :).

---

3 comments:

  1. Fine way of telling, and good piece of writing to take
    data concerning my presentation subject, which i am going to convey in university.


    Feel free to surf to my weblog; cara memulai bisnis properti

    ReplyDelete
  2. Hi! I know this is kinda off tοpic but I was wondering if ʏou knew where I could locate a captcha plugin for my comment form?
    I'm using the same blog platform as yours and I'm hаving trouble finding one?
    Thanks a lot!

    Hеre is my web paցe ... spyware and malware removal

    ReplyDelete