Handling Database updates with a RadioButtonList inside an ASP.NET GridView

Posted by: Suprotim Agarwal , on 1/23/2009, in Category ASP.NET
Views: 56009
Abstract: I have seen a couple of questions where users face issues while interacting with a RadioButtonList kept inside an ASP.NET GridView. On selecting one of the values of the RadioButtonList, the corresponding values should be updated in the database. For this, the respective row cell values and the radiobutton value should also be accessed, so as to update the correct row in the database corresponding to the row in the GridView. Let us see how.
Handling Database updates with a RadioButtonList inside an ASP.NET GridView
 
I have seen a couple of questions where users face issues while interacting with a RadioButtonList kept inside an ASP.NET GridView. The problem statement is as follows. Each row of the GridView contains a RadioButtonList control. On selecting one of the values of the RadioButtonList, the corresponding values should be updated in the database. For this, the respective row cell values and the radiobutton value should also be accessed, so as to update the correct row in the database corresponding to the row in the GridView.
In this article, I will address this issue and explain a simple solution to the problem. We will be taking the example of the Northwind database > ‘Products’ table and bind the ‘Discontinued’ column of the Products table with a RadioButtonList. Then on the selectedindexchanged event of the RadioButtonList, we will update the ‘Discontinued’ column in the database for that particular Product. This example will also show you how to access the RadioButtonList inside a row of the GridView that caused the postback and also how to access the other cells in that row.
Create a GridView and bind it to a SQL Data Source as shown below. Both the Select and Update Command have been configured:
      <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">
            <Columns>                          
                <asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" SortExpression="ProductID" />
                <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
                <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" SortExpression="QuantityPerUnit" />
                <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
            </Columns>
        </asp:GridView>
       
               <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], [UnitPrice], [Discontinued] FROM [Products]"
            UpdateCommand="UPDATE [Products] SET [Discontinued] = @Discontinued WHERE [ProductID] = @ProductID">
            <UpdateParameters>
                <asp:Parameter Name="Discontinued" Type="Boolean" />
                <asp:Parameter Name="ProductID" Type="Int32" />
            </UpdateParameters>
 
        </asp:SqlDataSource>
In your web.config, add a connection string as shown below:
 
      <connectionStrings>
            <add name="NorthwindConnectionString" connectionString="Data Source =(local);Integrated Security = SSPI; Initial Catalog=Northwind;"/>
      </connectionStrings>
 
Now add a <asp:TemplateField> to the GridView Column collection and add a RadioButtonList inside the ItemTemplate as shown below:
...
        <asp:TemplateField>
            <ItemTemplate>
                <asp:RadioButtonList AutoPostBack="true" ID="rbl" runat="server"
                    Enabled="true" SelectedIndex='<%#Convert.ToInt32(DataBinder.Eval(Container.DataItem , "Discontinued"))%>'
                    OnSelectedIndexChanged="rbl_SelectedIndexChanged">
                    <asp:ListItem Value="0">No</asp:ListItem>
                    <asp:ListItem Value="1">Yes</asp:ListItem>                       
                </asp:RadioButtonList>
            </ItemTemplate>
        </asp:TemplateField>               
    </Columns>
</asp:GridView>
 
As you can observe, the SelectedIndex is bound to the ‘Discontinued’ column.
We also have a ‘OnSelectedIndexChanged’ event where we will handle the database code as shown below:
C#
    protected void rbl_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        RadioButtonList rBtnList = (RadioButtonList)sender;   
            GridViewRow gvr = (GridViewRow)rBtnList.Parent.Parent;
        if(rBtnList.SelectedValue == "1")
            SqlDataSource1.UpdateParameters[0].DefaultValue = "True";
        else
            SqlDataSource1.UpdateParameters[0].DefaultValue = "False";
        SqlDataSource1.UpdateParameters[1].DefaultValue = gvr.Cells[0].Text;
        SqlDataSource1.Update();
        GridView1.DataBind();       
    }
VB.NET
      Protected Sub rbl_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
            Dim rBtnList As RadioButtonList = CType(sender, RadioButtonList)
            Dim gvr As GridViewRow = CType(rBtnList.Parent.Parent, GridViewRow)
            If rBtnList.SelectedValue = "1" Then
                  SqlDataSource1.UpdateParameters(0).DefaultValue = "True"
            Else
                  SqlDataSource1.UpdateParameters(0).DefaultValue = "False"
            End If
            SqlDataSource1.UpdateParameters(1).DefaultValue = gvr.Cells(0).Text
            SqlDataSource1.Update()
            GridView1.DataBind()
      End Sub
In the SelectedIndexChanged event, we retrieve the RadioButtonList that caused the postback. We then determine the GridViewRow to extract the value of the Cells in that row. Observe how we are using the Parent.Parent property to do so. Once we get this info, we use the update Parameters collection to update the changed value into the database.
Run the application. Each row of the GridView contains a RadioButtonList bound to the ‘Discontinued’ column. By default, ProductID 5 is discontinued. Select the value ‘No’ in the radiobuttonlist on that row with ProductID 5. A postback occurs and the value 'No' is updated in the database.
RBL
I hope you liked the article and I thank you for viewing it. The source code of this article can be downloaded from here.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Lineker Tomazeli on Wednesday, February 4, 2009 7:14 AM
thks..very nice
Comment posted by cdwang on Wednesday, April 8, 2009 3:37 AM
Hi , nice program.
I have problem in viewing the source code.

Please advise how should i view the source code.

regards
cdwang
Comment posted by Greg on Friday, April 10, 2009 5:25 PM
Fantastic article ! Really helped me out after I'd been banging my head on the desk for hours looking for an answer, thank you !
Comment posted by StinkyJak on Tuesday, October 13, 2009 7:15 AM
Thank you very much.
Comment posted by Irma on Thursday, October 29, 2009 2:25 PM
Excelente ejemplo... Era justo lo que necesitaba... Muchas gracias !!!
Comment posted by Chirag on Thursday, December 24, 2009 1:07 AM
string sel_gender=ds.Tables[0].Rows[0]["gender"].ToString();
            if(sel_gender.Trim().ToString()=="Male")
                rbl_gender.SelectedIndex=0;
            else
                rbl_gender.SelectedIndex=1;
Comment posted by Chirag on Thursday, December 24, 2009 1:08 AM
//can be done this way also
string sel_gender=ds.Tables[0].Rows[0]["gender"].ToString();
            if(sel_gender.Trim().ToString()=="Male")
                rbl_gender.SelectedIndex=0;
            else
                rbl_gender.SelectedIndex=1;
Comment posted by akhter hussain on Tuesday, June 29, 2010 3:09 AM
very nice article...
Comment posted by Dale Thomas on Friday, November 23, 2012 8:19 AM
Is there a way to have a column heading for the radiobutton column such as 'Discontinued'?
Comment posted by Dale Thomas on Friday, November 23, 2012 8:39 AM
Is there a way to have a column heading for the radiobutton column such as 'Discontinued'?
Comment posted by arrrrrr....hai on Wednesday, July 10, 2013 5:20 AM
wah
Comment posted by ashwani on Friday, February 28, 2014 11:38 PM
really very help full
thank u