Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidCastException on a list of objects

I have a query whose results look like

Blue
OrangeRed
Black
Green
Silver
Red

I intend to make a list of System.Drawing.Color objects out of this result set. When I run the program I'm getting the InvalidCastException. All of those colors are definitely in the enum of Color. Why am I getting this exception?

private List<System.Drawing.Color> BuildColorList()
    {
        List<System.Drawing.Color>ColorList = new List<System.Drawing.Color>();
        using (SqlConnection con = new SqlConnection(cs))
        {
            using (SqlCommand cmd = new SqlCommand("select color from Colors", con))
            {
                con.Open();
                cmd.CommandType = CommandType.Text;
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    System.Drawing.Color color = (System.Drawing.Color)rdr["color"];
                    ColorList.Add(color);
                }
            }
            return ColorList;
        }
    }
like image 974
wootscootinboogie Avatar asked Dec 08 '25 23:12

wootscootinboogie


2 Answers

You cannot do a cast: the query returns a System.String object, which cannot be cast to a System.Drawing.Color directly. Instead, you need to use Color.FromName(string) method instead:

private List<System.Drawing.Color> BuildColorList()
{
    List<System.Drawing.Color>ColorList = new List<System.Drawing.Color>();
    using (SqlConnection con = new SqlConnection(cs))
    {
        using (SqlCommand cmd = new SqlCommand("select color from Colors", con))
        {
            con.Open();
            cmd.CommandType = CommandType.Text;
            SqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                System.Drawing.Color color = System.Drawing.Color.FromName((string)rdr["color"]);
                ColorList.Add(color);
            }
        }
        return ColorList;
    }
}
like image 144
Sergey Kalinichenko Avatar answered Dec 11 '25 14:12

Sergey Kalinichenko


Replace this

System.Drawing.Color color = (System.Drawing.Color)rdr["color"];

with this

 System.Drawing.Color color =Color.FromName((string)rdr["color"]);
like image 29
Nikola Mitev Avatar answered Dec 11 '25 13:12

Nikola Mitev