Maintain State of the Selected Radio Button Inside the GridView
By AzamSharp
Views: 8146

Introduction:

 

Sometime ago I wrote an article in which I discussed how to get the selected value of a radio button control which resides inside the GridView control. You can read the article here. In this article I will demonstrate how to maintain the state of the selected HTML radio button across postbacks.

 

Populating the GridView Control:

 

The first task is to populate the GridView control. Take a look at the code below:

 

private void BindData()

    {

        string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true";

        SqlConnection myConnection = new SqlConnection(connectionString);

        SqlDataAdapter ad = new SqlDataAdapter("SELECT CategoryID, CategoryName FROM Categories", myConnection);

 

        DataSet ds = new DataSet();

        ad.Fill(ds);

 

        gvCategories.DataSource = ds;

        gvCategories.DataBind();      

 

    } 

 

The HTML source of the GridView control is given below:

 

<asp:GridView ID="gvCategories" runat="server" >

   

    <Columns>

   

    <asp:TemplateField>

    <ItemTemplate>

    <asp:Literal ID="litCategoryID" runat="server" />

    </ItemTemplate>

    </asp:TemplateField>

   

       

    <asp:TemplateField>

    <ItemTemplate>

    <asp:Literal ID="litCategoryName" runat="server" />

    </ItemTemplate>

    </asp:TemplateField>

   

    <asp:TemplateField>

    <ItemTemplate>

    <%# CreateRadioButton() %>

    </ItemTemplate>

    </asp:TemplateField>

   

    </Columns>

   

   

    </asp:GridView>  

 

You might notice that there are no radio buttons in the GridView control. This is because the radio buttons are dynamically injected when the GridView row is bind to the page. Let’s check out the CreateRadioButton method.

 

Maintaining Radio Button State Across Postbacks:

 

The CreateRadioButton method is responsible for dynamically injecting the radio buttons. Let's check out the method below: 

 

protected int index = 0;

protected string selectedValue = String.Empty;

 

protected string CreateRadioButton()

    {

        selectedValue = Request.Form["myRadioButton"] as String;

        string radioButton = String.Empty;

 

        if (!String.IsNullOrEmpty(selectedValue))

        {

            if (Int32.Parse(selectedValue) == index)

            {

                radioButton = "<input type='radio'  name='myRadioButton' id='myRadioButton' checked='checked' value='" + index + "'/>";

                index++;

                return radioButton;

            }

        }

               

        radioButton = "<input type='radio'  name='myRadioButton' id='myRadioButton' value='" + index + "'/>";                   

       

        index++;

        return radioButton;

    }

 

CreateRadioButton is fired the first time when the GridView is loaded. At that point none of the radio buttons are checked hence we return a simple HTML radio button. The only thing that distinguishes one radio button from the other is the value. I am generating sequential values for the radio buttons but you are free to use any values you want.

 

Now, let’s suppose that postback happens. The GridView is bind to the page and the CreateRadioButton method is called for each row. This time we have a value for the selected radio button which is captured in the Request.Form collection. We check that if the selected value belongs to any radio button value. Once, we find the radio button value that matches with the selected value we inject a radio button into the GridView row with its checked attribute set to “checked”. This action will cause the HTML radio button to be marked as checked and hence maintaining its state across postbacks.

 

I hope you liked this article, happy coding!

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Strange Behavior
Name: Danny Holyfield
Date: 5/1/2007 8:55:55 AM
Comment:
This works great between tags, but if you use , the function exhibits strange behavior ...
Subject: Good, but not quite
Name: Dave Baril
Date: 11/29/2007 7:04:58 AM
Comment:
This almost works, but the problem is that it only works if you re-bind the grid on every postback. If you're maintaining state on the grid itself, the grid doesn't get re-built and you lose the selection.

I accomplished it a different way. I set the radio button value to a unique value in the databind, then I added a hidden control to the template that is visible to .net that is bound to the same column as the radio button. I extract the value of the radio button via request.form as AZMSharp describes, but what I do differently is iterate through the grid on page.pre-render and look for the hidden control with the value that matches the value extracted with Request.Form. When I get a match, I replace the text in the cell containing the radio button in the grid with the code for a a selected radio button.

There is a slight performance hit from iterating through the grid on pre-render of course, but unless your grid is huge it won't be noticable, and it works whether or not you re-bind the grid. Also, doing it this way you can just drop the HTML Radio button into the template rather than building it in code.


Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
Dim gv As GridView = Me.gvResults
Dim txtId As New TextBox
Dim gvr As GridViewRow
For Each gvr In gv.Rows
txtId = gvr.FindControl("txtId")
If txtId.Text.Trim = strSelectedValue Then
gvr.Cells(0).Text = ""
End If
Next
End Sub



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008