none
C# Wimform Access DataBase RRS feed

  • Question

  • Hello All

    I have a Winform with a Access Data Base I am trying to add a picture to the Data Base. I'm getting the error (Failed to Convert parameter value from a Byte[] to a String). Access Data Type is OLE Object. I built this off another project that works fine.

    Any help much Appreciated 

     private void btn_Browse_Click(object sender, EventArgs e)
            {
                try
                {
                    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "JPEG|*.JPG", ValidateNames = true, Multiselect = false })
                    {
                        if (ofd.ShowDialog() == DialogResult.OK)
                            pictureBox1.Image = Image.FromFile(ofd.FileName);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
    
    
     private void btn_Save_Click(object sender, EventArgs e)
            {
                try
                {
                    Edit(false);
                    test_Trial_RosterBindingSource.EndEdit();
                    test_Trial_RosterTableAdapter.Update(rosterDataSet.Test_Trial_Roster);
                    test_Trial_RosterDataGridView.Refresh();
    
    
                    //   maskedTextBox2.Focus();
                    MessageBox.Show("You data has been Successfully saved.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    rosterDataSet.Test_Trial_Roster.RejectChanges();
                }
            }


    Booney440


    • Edited by Booney440 Sunday, September 22, 2019 2:50 PM update
    Sunday, September 22, 2019 2:36 PM

Answers

  • Hello,

    First off I've never recommend using TableAdapter method to work with data as much is hidden from the developer.

    Not sure what you mean by built off another project, perhaps there lies the problem. There is really nothing to use as the base code is in the designer file.

    Are you sure the database table schema has not be inadvertently changed or that the correct database is being used?

    Here is a working example that works with a old copy of Microsoft NorthWind database, specifically the Category table with a Ole Object field to store images. I placed a few random images under the Debug folder with the OpenFileDialog pointed to that folder. Give it a shot.

    https://1drv.ms/u/s!AtGAgKKpqdWjjVIr88C4NxHUFDIC?e=iLwCZo


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by Booney440 Tuesday, September 24, 2019 6:20 PM
    Sunday, September 22, 2019 3:53 PM
    Moderator
  • Hi Booney440,

    Thank you for posting here.

    According to your description, you want to add a picture to database.

    I write a simple code, you could have a look.

      private void button1_Click(object sender, EventArgs e) // check if the database contains the image
            {
                string connectionstring = @"";
                using (OleDbConnection conn = new OleDbConnection(connectionstring))
                {
                    conn.Open();
                    string sql = "select * from NewTable";
                    OleDbCommand command = new OleDbCommand(sql, conn);
                    OleDbDataReader reader = command.ExecuteReader();
                    int i = 0;
                    while (reader.Read())
                    {
                        byte[] b = (byte [])reader["Picture"];
                        if(i==0)
                        {
                            Image image = byteArrayToImage(b);
                            pictureBox1.Image = image;
                        }
    
                    }
    
    
    
                }
            }
    
            private void button2_Click(object sender, EventArgs e) // add a pictute to database
            {
                string connectionstring = @"";
                using (OleDbConnection conn = new OleDbConnection(connectionstring))
                {
                    conn.Open();
                    Image image = Image.FromFile(@"D:\Others\pic\5.jpg");
                    byte[] b = imageToByteArray(image);
                    string sql = "insert into NewTable(TechRole,Picture)values(@TechRole,@Picture)";
                    OleDbCommand command = new OleDbCommand(sql, conn);
                    OleDbParameter parameter1 = new OleDbParameter("@TechRole", OleDbType.VarChar);
                    parameter1.Value = "test1";
                    OleDbParameter parameter2 = new OleDbParameter("@Picture", OleDbType.VarBinary);
                    parameter2.Value = b;
                    command.Parameters.Add(parameter1);
                    command.Parameters.Add(parameter2);
                    command.ExecuteNonQuery();
                    MessageBox.Show("success");
    
    
                }
            }
    
            public byte[] imageToByteArray(Image imageIn)
            {
                MemoryStream ms = new MemoryStream();
                imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                return ms.ToArray();
            }
    
            public Image byteArrayToImage(byte[] byteArrayIn)
            {
                MemoryStream ms = new MemoryStream(byteArrayIn);
                Image returnImage = Image.FromStream(ms);
                return returnImage;
            }

    Database design:

    Test Result after inserting image to database:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Booney440 Tuesday, September 24, 2019 6:20 PM
    Monday, September 23, 2019 7:12 AM
    Moderator

All replies

  • Hello,

    First off I've never recommend using TableAdapter method to work with data as much is hidden from the developer.

    Not sure what you mean by built off another project, perhaps there lies the problem. There is really nothing to use as the base code is in the designer file.

    Are you sure the database table schema has not be inadvertently changed or that the correct database is being used?

    Here is a working example that works with a old copy of Microsoft NorthWind database, specifically the Category table with a Ole Object field to store images. I placed a few random images under the Debug folder with the OpenFileDialog pointed to that folder. Give it a shot.

    https://1drv.ms/u/s!AtGAgKKpqdWjjVIr88C4NxHUFDIC?e=iLwCZo


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by Booney440 Tuesday, September 24, 2019 6:20 PM
    Sunday, September 22, 2019 3:53 PM
    Moderator
  • Could you please explain the first line of the replay? First off I've never recommend using TableAdapter method to work with data as much is hidden from the developer.get the 

    i used the data source to get the accdb.


    Booney440

    Sunday, September 22, 2019 5:49 PM
  • Could you please explain the first line of the replay? First off I've never recommend using TableAdapter method to work with data as much is hidden from the developer.get the 

    i used the data source to get the accdb.


    Booney440

    I assumed test_Trial_RosterTableAdapter is a TableAdapter. I tried them once, have seen hundreds of people use them and all of them had issues with them. My personal issues are numerous starting with difficult to split into form and class projects, troublesome when making updates to the database when there are data bindings existing on a form and more that I just don't see working for apps that change over time.

    In regards to data source, if it's a TableAdapter responsible for interacting with data then it goes back to what I just wrote above.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Sunday, September 22, 2019 7:12 PM
    Moderator
  • Hi Booney440,

    Thank you for posting here.

    According to your description, you want to add a picture to database.

    I write a simple code, you could have a look.

      private void button1_Click(object sender, EventArgs e) // check if the database contains the image
            {
                string connectionstring = @"";
                using (OleDbConnection conn = new OleDbConnection(connectionstring))
                {
                    conn.Open();
                    string sql = "select * from NewTable";
                    OleDbCommand command = new OleDbCommand(sql, conn);
                    OleDbDataReader reader = command.ExecuteReader();
                    int i = 0;
                    while (reader.Read())
                    {
                        byte[] b = (byte [])reader["Picture"];
                        if(i==0)
                        {
                            Image image = byteArrayToImage(b);
                            pictureBox1.Image = image;
                        }
    
                    }
    
    
    
                }
            }
    
            private void button2_Click(object sender, EventArgs e) // add a pictute to database
            {
                string connectionstring = @"";
                using (OleDbConnection conn = new OleDbConnection(connectionstring))
                {
                    conn.Open();
                    Image image = Image.FromFile(@"D:\Others\pic\5.jpg");
                    byte[] b = imageToByteArray(image);
                    string sql = "insert into NewTable(TechRole,Picture)values(@TechRole,@Picture)";
                    OleDbCommand command = new OleDbCommand(sql, conn);
                    OleDbParameter parameter1 = new OleDbParameter("@TechRole", OleDbType.VarChar);
                    parameter1.Value = "test1";
                    OleDbParameter parameter2 = new OleDbParameter("@Picture", OleDbType.VarBinary);
                    parameter2.Value = b;
                    command.Parameters.Add(parameter1);
                    command.Parameters.Add(parameter2);
                    command.ExecuteNonQuery();
                    MessageBox.Show("success");
    
    
                }
            }
    
            public byte[] imageToByteArray(Image imageIn)
            {
                MemoryStream ms = new MemoryStream();
                imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                return ms.ToArray();
            }
    
            public Image byteArrayToImage(byte[] byteArrayIn)
            {
                MemoryStream ms = new MemoryStream(byteArrayIn);
                Image returnImage = Image.FromStream(ms);
                return returnImage;
            }

    Database design:

    Test Result after inserting image to database:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Booney440 Tuesday, September 24, 2019 6:20 PM
    Monday, September 23, 2019 7:12 AM
    Moderator
  • Karen excellent example but I see a table adapter in the example. what am I doing wrong in this project? Sorry to be so green but want to learn more I have no issue reading up just cant find anything.

    Thanks
       

    Booney440

    Tuesday, September 24, 2019 12:11 AM
  • Karen excellent example but I see a table adapter in the example. what am I doing wrong in this project? Sorry to be so green but want to learn more I have no issue reading up just cant find anything.

    Thanks
       

    Booney440

    Using TableAdapter means a good deal of stuff is done hidden for you under the covers (in the designer file) which means if everything is not in it's proper place you get issues like this while using a connection and command objects writing all the code yourself if something goes wrong we can look at the code and ask about the database table but with TableAdapter that is not possible.

    If all was correct under the covers of the designer file which the TableAdapter on the form uses and the database table was as expected there would be no issue.

    Bottom line with all that said I have nothing else to offer, sorry.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Tuesday, September 24, 2019 1:32 AM
    Moderator
  • Rebuilt it the way you suggested and all is working.

    Thank you for the help


    Booney440

    Tuesday, September 24, 2019 6:21 PM