i am trying to get the picture string from the database and when it is a null it gives me this error.


Unable to cast object of type 'System.DBNull' to type 'System.String


This is my code

public List<Item> GetAllItemFromMenuID(List<int> ListOfItemIDs)
        {
            conn.Open();
            List<Item> listOfItems = new List<Item>();
            

            try
            {
                foreach (int id in ListOfItemIDs)
                {
                    SqlCommand comm = new SqlCommand("Select * FROM tblItem WHERE ID = '" + id + "'", conn);

                    SqlDataReader r = comm.ExecuteReader();
                    while (r.Read())
                    {
                        string name = (string)r[1];
                        int itemType = (int)r[2];
                        decimal price = (decimal)r[3];

                        string picture = (string)r[4];
                        if (picture == null)
                        {
                            picture = "";
                        }

                        Item i = new Item(name, itemType, price, picture);

                        //Item i = new Item((string)r[1], (int)r[2], (decimal)r[3], picture);//(string) r[4]);

                        listOfItems.Add(i);
                    }
                    r.Close();
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
                return listOfItems;
            }

            finally
            {
                conn.Close();
            }
        


            return listOfItems;
        }

any solutions pls?

before line number 20 try to check the value of r[4] and if it is null then put null in picture string and if it is not null then convert it to string and perform other steps

Edited 5 Years Ago by abelLazm: n/a

if you want to check if the value is not null:

while (r.Read())
{  
   if(r.GetValue(1) != DbNull.Value)
     string name = (string)r[1];
   //and so on for the rest of the fields...
}

you mean something like this?

                 if ((string)r[4] == null)
                    {
                        MessageBox.Show("pic is null");
                    }

because i tried it annd didn't work. Could u give me an example pls?

Edited 3 Years Ago by Nick Evan: Fixed formatting

if you want to check if the value is not null:

while (r.Read())
{  
   if(r.GetValue(1) != DbNull.Value)
     string name = (string)r[1];
   //and so on for the rest of the fields...
}

whooohooo!! :D thx it worked :D thx very much.. happy easter 2 both and to abelLazm thx for trying to help ;)

If You find the solution then please mark this thread as solved

marked it already ;)

This question has already been answered. Start a new discussion instead.