Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1075
  • Last Modified:

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

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!.
  • 6
  • 5
2 Solutions
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 asp.net 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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
//Javascript fix to get around this bug
// http://support.microsoft.com/kb/316495
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.name)) 
				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()
            question1.quest = "what is the meaning of life?"
            lblQuestion.Text = question1.quest
            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

bolenkaAuthor Commented:
ok, thanks so much. I will take a look and get back to you.
bolenkaAuthor Commented:
will this work for radiobuttonlist?
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

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.
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.

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.
bolenkaAuthor Commented:
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.


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 vb.net 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 : http://support.microsoft.com/kb/316495

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.

bolenkaAuthor Commented:
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?
bolenkaAuthor Commented:
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:)
bolenkaAuthor Commented:
ONe more thing...so 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?

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 asp.net learning


Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 6
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now