Solved

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

Posted on 2008-10-28
12
1,027 Views
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

etc.

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!.
thanks.
0
Comment
Question by:bolenka
  • 6
  • 5
12 Comments
 
LVL 6

Expert Comment

by:AmarIs26
Comment Utility
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
http://support.microsoft.com/kb/316495
Fix
http://groups.google.com/group/microsoft.public.dotnet.framework.aspnet/msg/f2234ba565b8effa?dmode=source&output=gplain
 

<%@ 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;

}
 

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:Label ID="lblQuestion" runat="server" Text="Label"></asp:Label>

    <asp:ListView ID="ListView1" runat="server" >

            <LayoutTemplate>

                <table border="1">

                    <asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>

                </table>

            </LayoutTemplate>

            <ItemTemplate>

                <tr>

                    <td>

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

                        <span id="extraInfo" runat="server" visible="false">

                        </span>

                    </td>

                </tr>

            </ItemTemplate>

        </asp:ListView>

        <asp:Button ID="btnCheckAnswer" runat="server" Text="Check Answer" />

    </div>

    </form>

</body>

</html>
 
 

-----------------------------------
 

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

        Next
 

        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

        Get

            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

            ListView1.DataBind()
 

        End If

    End Sub
 

    Protected Function GetRandomPercentage() As String

        Dim rand As New Random()

        Threading.Thread.CurrentThread.Sleep(10)

        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

                Else

                    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
 

        Next

    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

0
 

Author Comment

by:bolenka
Comment Utility
ok, thanks so much. I will take a look and get back to you.
0
 

Author Comment

by:bolenka
Comment Utility
will this work for radiobuttonlist?
0
 
LVL 6

Expert Comment

by:AmarIs26
Comment Utility
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.
0
 
LVL 22

Accepted Solution

by:
prairiedog earned 250 total points
Comment Utility
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.

2008-10-29-145620.jpg
2008-10-29-145817.jpg
0
 
LVL 6

Expert Comment

by:AmarIs26
Comment Utility
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.
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

Author Comment

by:bolenka
Comment Utility
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.

0
 
LVL 6

Assisted Solution

by:AmarIs26
AmarIs26 earned 250 total points
Comment Utility

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

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

radiobutton.JPG
0
 

Author Closing Comment

by:bolenka
Comment Utility
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?
0
 

Author Comment

by:bolenka
Comment Utility
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:)
0
 

Author Comment

by:bolenka
Comment Utility
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?

wow.
0
 
LVL 6

Expert Comment

by:AmarIs26
Comment Utility
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
http://msdn.microsoft.com/en-us/library/ms644563.aspx
http://msdn.microsoft.com/en-us/asp.net/aa336567.aspx

 
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

So you have coded your own WordPress plugin and now you want to allow users to upload images to a folder in the plugin folder rather than the default media location? Follow along and this article will show you how to do just that!
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
In this tutorial viewers will learn how to customize the background color and font color of highlighted text using the ::selection element in CSS Begin by defining the selected text as an element in CSS by typing "::selection": Style the ::selection…
In this tutorial viewers will learn how to embed custom externally-hosted Google Fonts using the Google Font API in CSS Go to the Google Fonts website at google.com/fonts: Browse or search based on font properties or name to find a suitable font for…

762 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

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now