break

Convert a string into an enum

Have you ever come across something like this? I had, and I thought it was something interesting to write about.

The scenario:
I was using the AJAX AutoCompleteExtender when I realized that inside the ServiceMethod of my AutoCompleteExtender, I needed to call a method that needed between it’s parameters an Enum.

To the ServiceMethod of an AutoCompleteExtender, you can pass parameters through the contextKey. Nonetheless I couldn’t pass an enum, so I decided to pass the name of the Database as an string, and then inside the ServiceMethod convert the string into an enum.

Anyways, this is how you convert a string into an enum:

private void Form1_Load(object sender, EventArgs e)
{
DataBase db = convertStringToEnum("Pubs");
MessageBox.Show(db.ToString());
}
private DataBase convertStringToEnum(string dbName)
{
return (DataBase)Enum.Parse(typeof(DataBase), dbName);
}
public enum DataBase
{
Northwind = 0,
Pubs = 1
}

If you have any questions, feel free to leave a comment.

One Response

  1. TECNASA Says:

    Buenas tardes,necesitamos comunicarnos con usted, por favor me escribe al correo: mtrosas@tecnasa.com

    Gracias,

    María T. Rosas

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

CAPTCHA Image
Reload Image