skip to Main Content

I am using a radiobuttonlist in my ASPX page inside a Gridview :

<asp:GridView ID="grdRampPrepQues" runat="server" class="table table-dark table-striped" AlternatingRowStyle-BackColor="#eaeaea" ShowHeader="true"
                                    EmptyDataRowStyle-HorizontalAlign="Center" EmptyDataRowStyle-ForeColor="Red" OnRowCreated="grdRampPrepQues_RowCreated"
                                    OnRowDataBound="grdRampPrepQues_RowDataBound" ShowHeaderWhenEmpty="true" EmptyDataText="No Data Found !!"
                                    AutoGenerateColumns="false">

                                    <Columns>
                                        <asp:TemplateField HeaderText="Sl. No" ItemStyle-Width="4%" ItemStyle-HorizontalAlign="Center"
                                            HeaderStyle-CssClass="gridHeader" HeaderStyle-HorizontalAlign="Center" ItemStyle-CssClass="gridRow">
                                            <ItemTemplate>
                                                <%--<asp:Label ID="lblSno" runat="server" Enabled="false" Text="<%#Container.DataItemIndex+1%>"></asp:Label>--%>
                                                <asp:Label ID="lblSno" runat="server" CssClass="WrapText" Text='<%#Eval("QUES_NUM_SEQ") %>'></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>

                                        <asp:TemplateField HeaderText="Description" ItemStyle-Width="60%"
                                            ItemStyle-CssClass="gridRow" HeaderStyle-HorizontalAlign="Left" HeaderStyle-CssClass="gridHeader"
                                            ItemStyle-HorizontalAlign="Left">
                                            <ItemTemplate>
                                                <asp:Label ID="lblRampQues" runat="server" CssClass="WrapText" Text='<%#Eval("RAMP_PREP_QUES") %>'></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>


                                        <asp:TemplateField HeaderText="Response" ItemStyle-Width="20%"
                                            ItemStyle-CssClass="gridRow" HeaderStyle-HorizontalAlign="Center" HeaderStyle-CssClass="gridHeader"
                                            ItemStyle-HorizontalAlign="Center">
                                            <ItemTemplate>
                                                <asp:Label ID="lblRampQuesType" runat="server" Visible="false" CssClass="WrapText" Text='<%#Eval("QUES_TYPE") %>'></asp:Label>
                                                <asp:RadioButtonList ID="rblOptions" runat="server" RepeatDirection="Horizontal" Visible="false" CssClass="rbl">
                                                    <asp:ListItem Text="Yes" Value="Yes"></asp:ListItem>
                                                    <asp:ListItem Text="No" Value="No"></asp:ListItem>
                                                </asp:RadioButtonList>                                                
                                            </ItemTemplate>
                                        </asp:TemplateField>

                                    </Columns>
                                </asp:GridView>

I am getting the same radiobuttonlist control tagged to every question and I can select individual options particular to question:

enter image description here

Now the problem I am facing is at the backend while trying to store the data in database. I have a table in my database where I will be adding a new row every time somebody fills this form. In my C# code I have variables like these in which I need to store the values coming from the front when somebody clicks on the submit button and a event is triggered :

ques1 = radiobutton.selectedvalue;
ques2 = radiobutton.selectedvalue;
ques3 = radiobutton.selectedvalue;

Here I am not able to understand how to differentiate and get the values for each question’s radio button uniquely from the front.

Sorry for my English and thanks for helping me out.

2

Answers


  1. Sure, just keep in mind, that controls inside of the GridView repeat over and over. So, you don’t have "one" control say called rblOptions, but you have a "new" control with an ID generated for each row of the GridView.

    So, of course you can’t just use the control ID = rblOptions, since which row would it apply to?

    So, you have to use “FindControl" for each row in question.

    I don’t have your data, but this sample will show a working concept as to how you can save the selected RadioButtonList back into the database.

    So, say this GridView of some hotels, and we have an RadioButtonList to set if the room been inspected.

    So, this markup:

            <asp:GridView ID="GridView1" runat="server"
                AutoGenerateColumns="False" DataKeyNames="ID"
                CssClass="table table-hover" Width="50%"
                OnRowDataBound="GridView1_RowDataBound"
                >
                <Columns>
                    <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
                    <asp:BoundField DataField="LastName" HeaderText="LastName" />
                    <asp:BoundField DataField="City" HeaderText="City" />
                    <asp:BoundField DataField="HotelName" HeaderText="HotelName" />
                    <asp:BoundField DataField="Description" HeaderText="Descripiton" />
                    <asp:TemplateField HeaderText="Description">
                        <ItemTemplate>
                            <asp:RadioButtonList ID="rblOptions" runat="server"                                 
                                RepeatDirection="Horizontal"
                                >
                                <asp:ListItem Text="Yes" Value="Yes"></asp:ListItem>
                                <asp:ListItem Text="No" Value="No"></asp:ListItem>
                            </asp:RadioButtonList>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <PagerStyle CssClass="GridPager" />
            </asp:GridView>
    
    
    
            <asp:Button ID="cmdSave" runat="server" Text="Save/Done"
                CssClass="btn btn-dark"
                OnClick="cmdSave_Click"/>
    
            <asp:Button ID="cmdCancel" runat="server" Text="Cancel Changes"
                CssClass="btn btn-dark"
                OnClick="cmdCancel_Click"
                style="margin-left:35px"
                />
    

    So, code behind to load is this:

        DataTable dtHotels = new DataTable();
         protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
                Session["dtHotels"] = dtHotels;
            }
            else
            {
                dtHotels = (DataTable)Session["dtHotels"];
                }
        }
    
        void LoadData()
        {
            string strSQL =
                @"SELECT * FROM tblHotelsA
                WHERE Active = 1
                ORDER BY HotelName";
    
            dtHotels = General.MyRst(strSQL);
            GridView1.DataSource = dtHotels;
            GridView1.DataBind();
            
        }
    

    However, turns out some "extra" work is required, since our column in the database could be null (empty). Normally, we could just bind the RadioButtonList to an expression in the markup, but since we have null values, then that will not work.

    Hence, on row data bound, we test for null, and ONLY if a value exists, do we set the RB.

    Hence this code:

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow) 
            {
                RadioButtonList rbOption = (RadioButtonList)e.Row.FindControl("rblOptions");
                DataRowView gRowData = (DataRowView)e.Row.DataItem;
                
                if (gRowData["Inspected"].ToString() != "")
                        rbOption.Text = gRowData["Inspected"].ToString();
            } 
        }
    

    So, now the GV will display, and the user is free to choose/set each RB for each row.

    Our save button then has to send the choices back to the database table. Hence this code:

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            GridToTable();
    
            using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
            {
                string strSQL = "SELECT * FROM tblHotelsA";
                using (SqlCommand cmd = new SqlCommand(strSQL, conn))
                {
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    SqlCommandBuilder daU = new SqlCommandBuilder(da);
                    conn.Open();
                    da.Update(dtHotels);
                }
            }
    
            Response.Redirect("TestJump.aspx"); // navagate back to options page
    
        }
    
        void GridToTable()
        {
            // send grid rows back to table.
            foreach (GridViewRow rRow in GridView1.Rows)
            {
                DataRow OneDataRow = dtHotels.Rows[rRow.DataItemIndex];
                RadioButtonList rbOption = (RadioButtonList)rRow.FindControl("rblOptions");
    
                if (rbOption.Text != "")
                    OneDataRow["Inspected"] = rbOption.Text;
            }
        }
    

    So, above transfers the choices from each row of the GridView back to the data table, and then on "one" operation, we send all changes back to the database.

    The result is thus this:

    enter image description here

    And note how if I go back to the web page with the GridView, you can see my choices persist and are correctly saved back to the database.

    Hence this:

    enter image description here

    In summary, to get use of a control in ONE row of a GridView, then you have to get an instance of that one GridView row, and then use FindControl method of that GridView row, since that control exists "many" times in the page, and you have to resolve to the one row of controls you wish to obtain values from.

    Login or Signup to reply.
  2. To retrieve the selected value from the radio button from grid view controller you could loop through each row and backend code ad get the selected value, below is the code:

    Gridview:

     <form id="form1" runat="server">
            <div>
                   <asp:GridView ID="grdRampPrepQues" runat="server" AutoGenerateColumns="false" CssClass="table table-dark table-striped">
                       <Columns>
                           <asp:TemplateField HeaderText="Sl. No">
                               <ItemTemplate>
                                   <asp:Label ID="lblSno" runat="server" Text='<%# Container.DataItemIndex + 1 %>'></asp:Label>
                               </ItemTemplate>
                           </asp:TemplateField>
                           <asp:TemplateField HeaderText="Description">
                               <ItemTemplate>
                                   <asp:Label ID="lblRampQues" runat="server" Text='<%# Eval("RAMP_PREP_QUES") %>'></asp:Label>
                               </ItemTemplate>
                           </asp:TemplateField>
                           <asp:TemplateField HeaderText="Response">
                               <ItemTemplate>
                                   <asp:RadioButtonList ID="rblOptions" runat="server" RepeatDirection="Horizontal">
                                       <asp:ListItem Text="Yes" Value="Yes"></asp:ListItem>
                                       <asp:ListItem Text="No" Value="No"></asp:ListItem>
                                   </asp:RadioButtonList>
                               </ItemTemplate>
                           </asp:TemplateField>
                       </Columns>
                   </asp:GridView>
                   <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
               </div>
    
        </form>
    

    Backend code:

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebApplication1
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindGridView();
                }
            }
    
            private void BindGridView()
            {
    
                var questions = new List<Question>
                   {
                       new Question { QUES_NUM_SEQ = 1, RAMP_PREP_QUES = "Is the location identified and available?" },
                       new Question { QUES_NUM_SEQ = 2, RAMP_PREP_QUES = "Are the resources identified and available?" },
                       new Question { QUES_NUM_SEQ = 3, RAMP_PREP_QUES = "Is there sufficient participation for the programme?" }
                   };
    
                grdRampPrepQues.DataSource = questions;
                grdRampPrepQues.DataBind();
            }
    
            protected void btnSubmit_Click(object sender, EventArgs e)
            {
                List<string> responses = new List<string>();
    
                foreach (GridViewRow row in grdRampPrepQues.Rows)
                {
                    RadioButtonList rblOptions = (RadioButtonList)row.FindControl("rblOptions");
                    if (rblOptions != null)
                    {
                        string selectedValue = rblOptions.SelectedValue;
                        responses.Add(selectedValue);
                    }
                }
    
                // storing values in variables
                string ques1 = responses.Count > 0 ? responses[0] : string.Empty;
                string ques2 = responses.Count > 1 ? responses[1] : string.Empty;
                string ques3 = responses.Count > 2 ? responses[2] : string.Empty;
    
                // Save responses to database
                SaveResponsesToDatabase(ques1, ques2, ques3);
            }
    
            private void SaveResponsesToDatabase(string ques1, string ques2, string ques3)
            {
                string connectionString = ConfigurationManager.ConnectionStrings["RampPrepDB"].ConnectionString;
    
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    string query = "INSERT INTO RampPrepResponses (Question1, Question2, Question3) VALUES (@ques1, @ques2, @ques3)";
                    SqlCommand cmd = new SqlCommand(query, conn);
                    cmd.Parameters.AddWithValue("@ques1", ques1);
                    cmd.Parameters.AddWithValue("@ques2", ques2);
                    cmd.Parameters.AddWithValue("@ques3", ques3);
    
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
            }
    
            public class Question
            {
                public int QUES_NUM_SEQ { get; set; }
                public string RAMP_PREP_QUES { get; set; }
            }
        }
    }
    

    Result:

    enter image description here

    Data from Databse:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search