简体   繁体   中英

Specified cast is not valid - DataGridView

I'm building an application and I'm using a .dll that requires a param "Level" to be set to either gold, silver or bronze. Level is a public enum Level in the .dll.

To select either gold, silver or bronze I'd like to have it read from a dataGridView to save me from editing the source every time I want to change it however I keep getting the unhandles exception Specified cast is not valid.

This is my code.

var testLevel = dataGridView1.Rows[0].Cells[2].Value == null ? Level.All : (Level)(dataGridView1.Rows[0].Cells[2]).Value; // exception occurs on this line
var searchParameters = new PlayerSearchParameters
{
    Level = testLevel,
};

So, how could I go about making level read from the DVG correctly without problems?

Thanks.

Edit: I've tested it with comboBoxes and it works great, but I'd really like it to work via DGV.

You need to use Enum.Parse to parse string into enum you need.

Level levelValue = (Level) Enum.Parse(typeof(Level), (dataGridView1.Rows[0].Cells[2]).Value);  

Also use a check String.IsNullOrEmpty instead of dataGridView1.Rows[0].Cells[2].Value == null

As an example you can use:

Level levelValue;        
var value = dataGridView1.Rows[0].Cells[2]).Value;
if (Enum.IsDefined(typeof(Level), value))  
   levelValue = (Level) Enum.Parse(typeof(Level), value)
else
   levelValue = Level.All

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM