Get index of an enum by value

serkan sendur 0 Tallied Votes 3K Views Share

This is something very simple but very hard to find in google, it took me 30 minutes to solve it out. You have a value of type string and you want to get index number of that value in your enumeration, and now you can use that index number for corresponding value in your array.

//Default.aspx :

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
    </form>
</body>
</html>

// Default.aspx.cs

using System;

public partial class _Default : System.Web.UI.Page 
{
    public enum flags
    {
        serkan,
        ruslan,
        alexander
    }

    string[] myArray = { "sendur", "usmanov", "kravets" };
   
    protected void Page_Load(object sender, EventArgs e)
    {   
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        flags flag = (flags)Enum.Parse(typeof(flags), TextBox1.Text);
        Label1.Text = myArray[(int)(flags)flag];
    }
}


// when you run this application you will see that it returns you the lastname of
// the entered name, it keeps the names in enum, and the lastnames in array.
// it is useful when you dont want to have loops to find name value pairs.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.