سؤال

I am trying to get a picture from my Access Database into a Picturebox. But when I try to fill my DataRow whit the DataSet I get the following error:

Object reference not set to an instance of an object

Any help would be appreciated! I have the following code:

        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();
هل كانت مفيدة؟

المحلول

The ds.Tables["Pictures"] return a null, so you can't get the rows. Try:

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

or

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

نصائح أخرى

You need to check Dataset is Whether null or not before use it

Try like this

        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 مع الإسناد
لا تنتمي إلى StackOverflow
scroll top