How can I display text beside each radiobutton when loading a radiobutton list from an enumeration?

StackOverflow https://stackoverflow.com/questions/811693

  •  03-07-2019
  •  | 
  •  

Question

I am loading a radiobutton list from an enumeration (vertically displayed). I need to show text that describes each radiobutton selection. I am loading it in the codebehind.

Was it helpful?

Solution

There's quite a few aspects of the Enum class that I've found more and more uses for recently, and one of them is the GetNames Method. This method returns a string array of all of the names in a specified enum.

This code assumes you have a RadioButtonList on your page named RadioButtonList1.

public enum AutomotiveTypes
{
    Car,
    Truck,
    Van,
    Train,
    Plane
}

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string[] automotiveTypeNames = Enum.GetNames(typeof(AutomotiveTypes));

        RadioButtonList1.RepeatDirection = RepeatDirection.Vertical;

        RadioButtonList1.DataSource = automotiveTypeNames;
        RadioButtonList1.DataBind();
    }
}

Give that a spin, and see if it does the trick for ya.

Cheers!

OTHER TIPS

You should be able to use the .Text property on the control.

http://www.w3schools.com/ASPNET/control_radiobutton.asp

EDIT:

Actually I think miss-read the question, I believe this is what you are looking for

For Each val As [Enum] In [Enum].GetValues(GetType(YourEnum))
        Radio Button Add Logic Here
Next

A couple ideas are to either have a dictionary that maps description strings to enum values, or you can decorate your enum values with an attribute.

I've got a little library, same code etc, that provides a nice interface for using attributes on enums for this very purpose.

http://daniel-mcadam.com/blog/2009/11/05/User-Display-Text-For-Enums.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top