当记录存在时,无法将“System.DBNull”类型的对象强制转换为“System.Byte []”

时间:2015-01-15 08:49:46

标签: c# mysql asp.net webforms ado.net

我试图从MYSQL读取和下载BLOB。虽然记录存在,但我仍然继续得到这个错误。以下是我的代码:

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();

            }

请告诉我如何消除此错误。

2 个答案:

答案 0 :(得分:5)

可能是记录存在,但错误告诉您proposalDoc是db null。所以灵魂就是检查它是否为db null:

if(!Convert.IsDBNull(r["proposalDoc"]))
{
    bytes = (byte[])r["proposalDoc"];
}

答案 1 :(得分:0)

!string.IsNullOrEmpty(r["proposalDoc"].ToString())?(byte[])r["proposalDoc"] : null