簡體   English   中英

你調用的對象是空的。 錯誤

[英]Object reference not set to an instance of an object. Error

我正在嘗試將Access數據庫中的圖片放入Picturebox。 但是,當我嘗試填充數據集的DataRow時,出現以下錯誤:

你調用的對象是空的

任何幫助,將不勝感激! 我有以下代碼:

        OleDbConnection conn = new OleDbConnection(constr);
        conn.Open();

        string cmdstr = "SELECT Picture FROM Gegevens WHERE ID =" + id;
        OleDbCommand cmd = new OleDbCommand(cmdstr, conn);           
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);

        DataSet ds = new DataSet();
        da.Fill(ds, "picture");

        DataRow dr = ds.Tables["Pictures"].Rows[0]; //Here i get the error!

        byte[] result = (byte[])dr["Picture"];
        int ArraySize = result.GetUpperBound(0);

        MemoryStream ms = new MemoryStream(result, 0, ArraySize);
        Picturebox1.Image = Image.FromStream(ms);

        conn.Close();

ds.Tables [“ Pictures”]返回null,因此無法獲取行。 嘗試:

ds.Tables[0].Rows[0]; 

要么

ds.Tables["picture"].Rows[0];

您需要先檢查數據集是否為空

這樣嘗試

        OleDbConnection conn = new OleDbConnection(constr);
        conn.Open();

        string cmdstr = "SELECT Picture FROM Gegevens WHERE ID =" + id;
        OleDbCommand cmd = new OleDbCommand(cmdstr, conn);           
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);

        DataSet ds = new DataSet();
        da.Fill(ds, "picture");

        if (ds != null && Data.Tables[0].Rows.Count > 0)
        {
        DataRow dr = ds.Tables["Pictures"].Rows[0]; //Here i get the error!

        byte[] result = (byte[])dr["Picture"];
        int ArraySize = result.GetUpperBound(0);

        MemoryStream ms = new MemoryStream(result, 0, ArraySize);
        Picturebox1.Image = Image.FromStream(ms);
        }
        conn.Close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM