How do I append a checkmark image to a radiobuttonlist item if the user has selected the correct answer?

Posted on 2008-10-28
Last Modified: 2013-12-26
Hi, I really need help with specific code examples in VB on this.

How do I :
1) Specifically add an small image to a specific radiobuttonlist item. For example: the user selects an item, I am already adding a new attribute to change the color of the radiobuttonlist item to GREEN if the answer is correct. But the client also wants an image to appear (ansR.gif if Correct, and ansW.gif if INCORRECT)
I tried adding a background image url to my css class, but it does not seem to be working.

2) For each specific ListItem, after the user has selected an answer, I want to show statistics about the answer for each listitem:
For example:
*Answer1     88% have chosen this answer
Answer2      12% have chosen this answer


I am binding the radiobuttonist to a userdefined function that gives me the data that I need for the radiobuttonist.. I am using a sql datasource to select and bind the radiobuttonlist to the returned table in the userdefined function.

How in the world do I show these images after the userclicks an answer?
What in the world is the best way to display the statistical data for each radiobuttonlist item.

I cant just use one label for all of them, because there is not a fixed number of radiobuttonlist items to chose from...since the radiobuttonlist items can change everytime, would the best way to add the statistics be to append the percentages to the rendered label text?

PLease help!.
Question by:bolenka
  • 6
  • 5

Expert Comment

ID: 22823197
Hello Again, I figured it would be fast to create a sample for you. Using this you can basically design your own radiobutotnlist, and add any amount of elements along with your radiobutton.
Took about 5 minutes to create but then i came across this bug in to do with Radiobuttons. anyways the following sample will dowhat you need and includes the fix.
you can read about the problem here

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default3.aspx.vb" Inherits="Default3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
//Javascript fix to get around this bug
function SetUniqueRadioButton(nameregex, current)
	re = new RegExp(nameregex);  
	for(i = 0; i < document.forms[0].elements.length; i++) 
		elm = document.forms[0].elements[i]
		if (elm.type == 'radio') 
			if (re.test( 
				elm.checked = false;
	current.checked = true;
    <form id="form1" runat="server">
        <asp:Label ID="lblQuestion" runat="server" Text="Label"></asp:Label>
    <asp:ListView ID="ListView1" runat="server" >
                <table border="1">
                    <asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
                        <asp:RadioButton ID="Radio1" runat="server"  GroupName="answers" />
                        <asp:Label ID="lblText" runat="server" Text='<%#Eval("Answer") %>' ></asp:Label>
                        <span id="selectText" runat="server" visible="false">
                         [ Selected Answer ]
                        <span id="extraInfo" runat="server" visible="false">
        <asp:Button ID="btnCheckAnswer" runat="server" Text="Check Answer" />
Public Class Question
    Public quest As String
    Public Answers(3) As Answer
    Public Sub New()
        For count As Integer = 0 To 3
            Answers(count) = New Answer
        Answers(0).Answer = "Answer 1"
        Answers(1).Answer = "Answer 2"
        Answers(2).Answer = "Answer 3"
        Answers(3).Answer = "Answer 4"
    End Sub
End Class
Public Class Answer
    Dim ans As String
    Public Property Answer() As String
            Return ans
        End Get
        Set(ByVal value As String)
            ans = value
        End Set
    End Property
End Class
Partial Class Default3
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If (Not Page.IsPostBack) Then
            Dim question1 As New Question()
   = "what is the meaning of life?"
            lblQuestion.Text =
            ListView1.DataSource = question1.Answers
        End If
    End Sub
    Protected Function GetRandomPercentage() As String
        Dim rand As New Random()
        Return String.Format("{0}% have chosen this answer", rand.Next(1, 100))
    End Function
    Protected Sub btnCheckAnswer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCheckAnswer.Click
        For Each item As ListViewItem In ListView1.Items
            Dim radioButton As RadioButton
            radioButton = item.FindControl("Radio1")
            If (Not radioButton Is Nothing) Then
                If (radioButton.Checked = True) Then
                    item.FindControl("selectText").Visible = True
                    item.FindControl("selectText").Visible = False
                End If
            End If
            Dim extraInfo As HtmlGenericControl
            extraInfo = item.FindControl("extraInfo")
            If (Not extraInfo Is Nothing) Then
                extraInfo.InnerText = GetRandomPercentage()
                extraInfo.Visible = True
            End If
    End Sub
    Protected Sub ListView1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles ListView1.ItemDataBound
        Dim script As String = "SetUniqueRadioButton('ListView1.*answers',this)"
        Dim rb As RadioButton = e.Item.FindControl("Radio1")
        rb.Attributes.Add("onclick", script)
    End Sub
End Class

Open in new window


Author Comment

ID: 22823878
ok, thanks so much. I will take a look and get back to you.

Author Comment

ID: 22823925
will this work for radiobuttonlist?
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Expert Comment

ID: 22825625
it creates an advance radiobutton list. it basically creates a table with dynamic rows for your answers. In each row it adds a radio button and a label. But because you have full control over the row and cells you can add anything else with it as well , like images, text in the same row.
Try the sample to see how it works.
LVL 22

Accepted Solution

prairiedog earned 250 total points
ID: 22834968
There is actually an easier way to do it.
In you code behind, when you find the user's selection is the correct answer, you can modify the RadioButtonList.SelectedItem.Text by appending a "<img>" tag in it, like this:
For correct answer:
Me.RadioButtonList1.SelectedItem.Text = Me.RadioButtonList1.SelectedItem.Text & "&nbsp;<img src='" & Request.ApplicationPath & "/Images/ansR.gif'>"
For wrong answer, just change the above file name.


Expert Comment

ID: 22836608
While the above solution solves this issue, it is not very maintainable. For example, what happens if there is a need to provide extra controls which all have events etc on the same line as the radiobutton. The string concatanation method will mean having to provide hacks to do postback to the server as the controls rendered with string concatanation will not be registered.
At the same time one could argue that the solution i provided relies on javascript :) but thats a limitation of radiobutton control inside a control which implements INamingContainer.

Author Comment

ID: 22837616
thank you both for your responses, but, Amaris 26, can you explain what you mean by a "hack"? I am not sure I know what that is, even though, I have heard that term a few times.

So, do you mean that if I have to concatenate other information to the radiobuttonlistitem other than the correct or incorrect image, that I should not append the image to the string? For example, If I need a radiobutton item to show an image for the correct or incorrect answer + the radiobuttonlistitem text + a percentage for an answer, will prariedog's solution work? I don't forsee having to add any other control with events although, I appreciate your warning about maintaining the list. I would not have thought of that unless you mentioned it.

Also, would you mind explaining the implications of using a control with the iNamingContainer if you would? I am not sure what that is either, but look forward to hearing your explanation as I am learning so much from yours and all ofthe expert's comments. thank you both for your responses thus far.


Assisted Solution

AmarIs26 earned 250 total points
ID: 22839068

This is the fun of software development. You often have a number of solutions to a problem. Deciding which one to go with is the fun part.

I will explain what i mean by maintainable:

Look at the attached image,  on the same row as the radio button you have  text, image, percentage label  and posibility of adding other controls inthe future. Using the code sample i provided you can easily add as many more controls as you want and each of these controls could be referenced in your code behind and also can have their own events e.g a linkbutton in this row would do a postback.

Now consider the string concatanation method.
to attach the image + percentage label + other future control you have to keep building up this string.

Me.RadioButtonList1.SelectedItem.Text = Me.RadioButtonList1.SelectedItem.Text & "&nbsp;<img src='" & Request.ApplicationPath & "/Images/ansR.gif'>"  & "<label id='' text=''/>" & "Lots of other html for other controls"

now as you add more controls (you may never) that string is going to get bigger and harder to maintain. But the big disadvantage is that the controls rendered using that method can not be referenced in your code and also adding events to them will not be easy. This is what i meant by hack, for example lets say i want to have a link in this row that will do a postback to the server and then display more information about the answer somewhere on the page.

So in my code all you would have to do is this, Add a new linkbutton to the  <tr><td> in the <ItemTemplate>

<asp:linkbutotn id="moreinfolink" runat="server" commandname="moreinfo" commandargument="answerid"/>

Then you simply handle the OnCommand event of the listview control and look for that command.

If i wanted to do this with string concatanation
you would have to add the html for the linkbutton to the radiobutton text. Then you would have to write some javascript to raise a postback to the server do execute the code that gets more information. (This becomes even more comlpicated if you want to do the postback inside an updatepanel).
As for INamingContainer problem :

When you add a ASP.NET RadioButton control to the ItemTemplate of a data-bound Repeater server control, the RadioButton control that you created is not mutually exclusive when you run the ASP.NET page. This problem occurs even if the GroupName attribute is set for the RadioButton controls.
Back to the top
This problem occurs because the Repeater server control implements the INamingContainer interface, which requires that all controls that are nested within it must have a unique name when rendered in Hypertext Markup Language (HTML). Therefore, the HTML name attribute of any rendered child server control is unique.
Basically, for only one radiobuttons to be selected at one time they all must belong to same group, this way all radiobuttons in same group can only have one selected. But when a parent control e.g. Repeater, Listview renders its children it changes their ID's so they are always unique. Doing this means that everyradio button in listview now has different id/name and they no longer belong to same group.
Anyways, to make things easier for you, if you have no requirements to add anymore controls in the same row as radio button and dont think any of those controls will be raising any events then prairiedog's solution is simple and works best.


Author Closing Comment

ID: 31511614
Prairie Dog: Thanks so much, for the solution.  Amaris has been working on this and very helpful as well. I have learned so much from both of you, so I am splitting points. thanks so much.
AmarIs26: You have been so great at answering my followups, so I am splitting points. This information has been invaluable to me on this project. I hope to hear from you both again. Thank you so much.
Seems like just when I think I know enough about ASP.NET there si so much more to learn. Do either of you know the best way to take some classes online? I would really like to find some advanced classes that I can take that will go into detail about each control etc....things that are not readily available in the ASP.NET book that I bought.  How did you all learn what you know?

Author Comment

ID: 22839948
Ok, I just read your post about the bug...I had originally tried using radiobuttons, not radiobuttonlist...which maybe why I could not get it to work. It was literally driving me crazy. Thanks so much for this bug alert. What a pain. Turns out, I am not crazy...of course...thanks to you guys:)

Author Comment

ID: 22839973
ONe more basically what the bug says is that the radiobuttongroup won't work if you have your radiobuttons in another control like formview...
or is it not formview?
Just a datagrid that gives it a specific row layout?


Expert Comment

ID: 22840087
Hi Bolenka,
I dont know about formview but in datagrid/gridview  for sure you will get this bug.  Mainly any control that repeates information , most likely will cause this problem.
Anyways, here are some  good links to learning


Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes some techniques which will make your VBA or Visual Basic Classic code easier to understand and maintain, whether by you, your replacement, or another Experts-Exchange expert.
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
In this tutorial viewers will learn how to position overlapping items using z-index in CSS. They will also learn the restrictions on the z-index property.  Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Red.…
In this tutorial viewers will learn how to style transparent/translucent elements using alpha transparency in CSS Start with a normal styled element, such as a div.: Define its "background-color" property as "rgba (255, 255, 255, .5): The numbers in…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question