Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]' when record does exist

Im trying to read and download BLOB from MYSQL. Even though the record exist but still I keep on getting this error . Following is my code:

this.Time = String.Format("{0:HH:mm:ss}", DropDownList1.SelectedValue);
            String query = "Select * from event where time='" + this.Time + "'";
            MySqlConnection conn = new MySqlConnection(connection);
            MySqlCommand cmd = new MySqlCommand(query, conn);
            String time = String.Format("{0:t}", DateTime.Today);
            conn.Open();
            MySqlDataReader r = cmd.ExecuteReader();   
            while (r.Read())
            {
                TextBox1.Text = r["name"].ToString();
                TextBox2.Text = r["Proposedby"].ToString();
                bytes = (byte[])r["proposalDoc"];    
                TextBox5.Text = Calendar1.SelectedDate.ToString("d");
                TextBox6.Text = r["time"].ToString();
                TextBox7.Text = r["Society"].ToString();
                TextBox8.Text = r["venue"].ToString();

            }

kindly tell how I can eliminate this error.

like image 660
puffles Avatar asked Dec 25 '22 00:12

puffles


1 Answers

It might be that the record exists but the error tells you that the proposalDoc is db null. So the soultion would be to check if it is db null like this:

if(!Convert.IsDBNull(r["proposalDoc"]))
{
    bytes = (byte[])r["proposalDoc"];
}
like image 192
Arion Avatar answered Jan 01 '23 04:01

Arion