Search code examples
c#asp.netradiobuttonlist

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


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.


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!