C# – Unable to cast object of type ‘System.DBNull’ to type ‘System.Byte[]’ when record does exist

ado.netasp.netcMySQLwebforms

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.

Best Answer

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"];
}
Related Topic