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

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?

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 look at the post of mitja you will find what I mean

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

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

marked it already ;)

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.