Discovering the selected RadioButton within a Repeater Item: a step-by-step guide

The ASPX-page contains a Repeater control defined as follows:

<asp:Repeater ID="answerVariantRepeater" runat="server"
    onitemdatabound="answerVariantRepeater_ItemDataBound">
    <ItemTemplate>
        <asp:RadioButton ID="answerVariantRadioButton" runat="server"
            GroupName="answerVariants" 
            Text='<%# DataBinder.Eval(Container.DataItem, "Text")%>'"/>
    </ItemTemplate>
</asp:Repeater>

To ensure that only one radio button can be selected at a time, a solution from this article was implemented.

Now, upon form submission, there is a need to determine which radio button has been checked.

One way to achieve this is through the following code snippet:

RadioButton checkedButton = null;

foreach (RepeaterItem item in answerVariantRepeater.Items)
{
    RadioButton control=(RadioButton)item.FindControl("answerVariantRadioButton");
    if (control.Checked)
    {
        checkedButton = control;
        break;
    }
}

However, there might be a simpler approach, possibly utilizing LINQ to objects.

Answer №1

To retrieve the selected radio button, you can make use of Request.Form:

var value = Request.Form["answerVariants"];

The default submitted value is usually the id of the selected <asp:RadioButton />, but you have the option to include a value attribute for a custom submission:

<asp:RadioButton ID="answerVariantRadioButton" runat="server"
    GroupName="answerVariants" 
    Text='<%# DataBinder.Eval(Container.DataItem, "Text")%>'"
    value='<%# DataBinder.Eval(Container.DataItem, "SomethingToUseAsTheValue")%>' />

Answer №2

Utilizing JavaScript for managing the radio button click event on the client enables you to simultaneously update a hidden field with the chosen value.

Subsequently, your server-side code can easily retrieve the selected value from the hidden field.

Answer №3

Utilizing LINQ to Objects in this scenario seems limited to transferring the conditions inside the foreach loop into a where clause.

RadioButton selectedButton = 
    (from element in answerVariantRepeater.Elements
    let radioBtn = (RadioButton)element.GetControl("answerVarRadioBtn")
    where radioBtn.Checked
    select radioBtn).First();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Calculate the sum of elements with JavaScript

I am working with an array where each element is an object that also contains an array. My goal is to calculate the sum of all items in the nested arrays. Here is the approach I have attempted: function getSum(total, item) { return total + item; } v ...

Updating data from an ajax call in chart.js can be done with a few simple steps

I have successfully generated a graph using data from an ajax call in a php file. Now, I want to enhance this graph by allowing users to select a specific customer from a drop-down list (chg_customer) and display the corresponding count on the chart. Altho ...

What is the best way to retrieve search queries from suggestqueries.google.com through a fetch request, or is there another method to obtain Google suggestions?

https://i.sstatic.net/1rTiC.png I have recently created a Vue.JS new tab page and I'm looking to integrate Google suggestions into the search bar. After some research, I stumbled upon an API that seems like it could help me achieve this. However, whe ...

Is dividing a website into two parts acceptable?

In the process of creating a social network, one major concern is making sure that the content is easily readable by Google while also providing users with a seamless and engaging experience through Ajax support. However, it's well-known that Ajax and ...

Having trouble getting the Div to fade in on Page load after a 2 second delay?

I am currently facing an issue with a div element that I am trying to make fade in after a 2-second delay upon page load using JavaScript/jQuery. Unfortunately, my attempts have been unsuccessful as the div does not fade in at all. Could someone please as ...

Should I use "npm install" or "sudo npm install -g"

When it comes to installing certain packages, sometimes running sudo npm install -g is necessary, while for others simply using npm install is enough. What causes this difference and why does it exist? Take the following examples: npm install -g grunt-c ...

methods for converting an array to JSON using javascript

Our team is currently working on developing a PhoneGap application. We are in the process of extracting data from a CSV file and storing it into a SQLite database using the File API in PhoneGap. function readDataUrl(file) { var reader = new FileReade ...

The menu field remains open even after clicking on the menu

I have encountered an issue with my code. Here is a DEMO that I created on jsfiddle.net Currently, when you click on the red div, the menu opens. However, if you click on the menu items, the menu area does not close. What do I need to do in order to clo ...

What is the process for transforming promises into async await syntax?

login() { return new Promise((resolve, reject) => { userCollection.findOne({email: this.data.email}).then((myUser)=>{ if (myUser && myUser.password == this.data.password) { resolve("Congrats! Succe ...

Verifying conditions within an array of objects in JavaScript

Verify an array of objects based on certain conditions. The array of objects starts off empty. 1. If the array is empty and an action occurs, add an object to the array. 2. If the array already contains an object, check if it already exists. If it does, ...

What is the method to dynamically update the header with JavaScript?

I am struggling to achieve consistent vertical alignment from the top for all title fields. In other words, I want to assign the same top value to each title field so they are aligned at the top. To illustrate this issue, let's consider a live site & ...

Verify if a checkbox is selected upon loading the page

Hey there, I have a jQuery change function set up to turn an input text box grey and read-only when a user selects a checkbox. However, I'm interested in adding a check on page load to see if the checkbox is already selected. Any suggestions for enhan ...

Closing one specific tab will result in the closure of all other tabs as well

I am experiencing an issue where closing a specific tab results in all tabs being closed instead of just the intended one. I need assistance in making sure only that particular tab is closed. remove = targetKey => { let { activeKey } = this.state; ...

What could be causing a syntax error when I use `npm run start` with npm react-scripts?

After months of working on a full stack React app, I encountered an unexpected error when trying to run npm run start from the command line. The error message was as follows: // npm run start > [email protected] start /Users/eden/Documents/GitH ...

Leveraging the power of the Microsoft Graph API to retrieve upcoming events from Outlook

Apologies for the broad nature of this question, but it accurately reflects the task at hand. Within my organization, I am working on consolidating events from specific individuals' calendars and integrating them into a shared calendar. Essentially, ...

Shutting down the server following the completion of the mocha test, yet the data remains intact

Currently, I am working on testing some data using a REST API. The data is stored as an array within the project. My goal is to have the data "reset" every time a test suite runs, so that I can accurately determine the amount of data in the array. Howeve ...

Tips for linking ASP.NET Crystal Reports with MySQL

Is there a way to connect ASP.NET Crystal Report with a MySQL database, similar to how one would connect it with a SQL Server database? Are there any connectors specifically designed for this purpose? ...

An error occurred with Express and Passport: ['ERR_HTTP_HEADERS_SENT']

Currently, I am diving into an ebook tutorial and have encountered a roadblock in a particular piece of code. The code is designed to take a username and password in JSON format through Insomnia or Postman, and it should return a login success cookie. Howe ...

Automatically updating div content using a static HTML page

Is there a way to refresh the content of an HTML div tag every 5 minutes without having to reload the entire page? <div id="pie"> <script src="index.js">// this script should be reloaded every 5 minutes </script& ...

How to customize text within an HTML <option> tag within a <select> element

Customizing the appearance of items in an option list can be easily achieved by using CSS: <select> <option>Option 1</option> <option style="color: #F00; font-weight: bold; padding-left:2em;">Option 2</option> <opt ...