ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

C# program that interfaces with MS Access: Store data (text, image) in an Access database file

Updated on December 3, 2009

1.      Open a new Visual C# .NET windows application. Name the project CreateDatabase.

2.      Design a form. Add three Textboxes and two Buttons

3.      Set Name property of Textboxes to “txtDatabase”, “txtStudentName” and “txtStudentPicture”.

4.      Set Name property of Buttons to “btnCreateTable” with text property “Create Table” and “btnSave” with text property “Save”.

5.      In the code file add namespace:

using System.Text;

using System.Data.OleDb;

6.      Double click on the Button “Create Table” and pest the following code into the “btnCreateTable_Click” event.


OleDbCommand Cmd; 
string SQL = "";  
OleDbCommand objCmd = new OleDbCommand(); 
 
OleDbConnection Con = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;data
source=" + txtDatabase.Text + "");
 
SQL = "CREATE
TABLE tblStudentInfo ([StudentID] COUNTER, [StudentName] TEXT(50), [Picture]
OLEObject)";
Cmd = new
OleDbCommand(SQL, Con);
 
      Con.Open();
      objCmd = new OleDbCommand(SQL,
Con);
     
objCmd.ExecuteNonQuery();
   Con.Close();

7.      Double click on the Button “btnSave” and pest the following code into the “btnSave_Click” event.

StoreData(ImageToStream(txtStudentPicture.Text));

8.      Add the following modules to the code file.

private byte[] ImageToStream(string fileName)

     {
        Bitmap image = new Bitmap(fileName);
        MemoryStream stream = new
MemoryStream();
       
image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
        return stream.ToArray();
     }
 
    private void
StoreData(byte[] content)
     {
 
OleDbConnection
conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;data source="
+ txtDatabase.Text + "");
    
conn.Open();
 
     if (conn.State.Equals(ConnectionState.Closed))
        
conn.Open();
         try
         {
OleDbCommand insert = new OleDbCommand("Insert into tblStudentInfo (StudentName,Picture)
values(@StudentName,@image)", conn);
 
OleDbParameter
picParameter = insert.Parameters.Add("@StudentName",
OleDbType.VarChar );
              
picParameter.Value = txtStudentName.Text;
              
picParameter.Size = 50;
OleDbParameter
imageParameter =  insert.Parameters.Add("@image", SqlDbType.Binary);
              
imageParameter.Value = content;
              
imageParameter.Size = content.Length;
              
insert.ExecuteNonQuery();
               MessageBox.Show("Data
Stored successfully"); 
         }
         catch (Exception ex)
            {
               MessageBox.Show(ex.Message.ToString());
               MessageBox.Show(ex.StackTrace.ToString());
            }
         finally
            {
              
conn.Close();
            }
  }

9.      Press F5 to build and run the project.

Put your database name with location like c:\MyAccessDB in the text box “txtDatabase”, put student name in the text box “txtStudentName” and put student picture path in the text box “txtStudentPicture” then press the “Create Table” Button and after that press “Save” button to save the student information to the database table.

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Jay Prakash 

      4 years ago

      Have a look at here

      Using Access Database with c# -- geeksprogrammings.blogspot.com

      http://geeksprogrammings.blogspot.com/2013/10/conn...

      For Deletion Record

      http://geeksprogrammings.blogspot.com/2013/09/dele...

    • profile image

      martellawintek 

      5 years ago

      yous ok toni if your still hanging around i think this is the site

      and some info , they have a deal on at the mo , mention marta gift him out

    • profile image

      Ramchandra jha 

      6 years ago

      Sorry.......This programe is not run

      So plz help me

      Error:-

      Error 1 Newline in constant F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 27 43 CreateDatabase

      Error 2 Newline in constant F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 28 32 CreateDatabase

      Error 3 Newline in constant F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 30 7 CreateDatabase

      Error 4 Newline in constant F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 32 11 CreateDatabase

      Error 5 Newline in constant F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 75 40 CreateDatabase

      Error 6 Newline in constant F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 76 28 CreateDatabase

      Error 7 Newline in constant F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 93 32 CreateDatabase

      Error 8 Newline in constant F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 94 20 CreateDatabase

      Error 9 Expected class, delegate, enum, interface, or struct F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 49 13 CreateDatabase

      Error 10 Identifier expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 49 18 CreateDatabase

      Error 11 Expected class, delegate, enum, interface, or struct F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 49 20 CreateDatabase

      Error 12 Expected class, delegate, enum, interface, or struct F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 52 28 CreateDatabase

      Error 13 Expected class, delegate, enum, interface, or struct F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 54 1 CreateDatabase

      Error 14 Expected class, delegate, enum, interface, or struct F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 60 13 CreateDatabase

      Error 15 Identifier expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 61 16 CreateDatabase

      Error 16 Expected class, delegate, enum, interface, or struct F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 61 18 CreateDatabase

      Error 17 Expected class, delegate, enum, interface, or struct F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 65 12 CreateDatabase

      Error 18 Expected class, delegate, enum, interface, or struct F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 75 27 CreateDatabase

      Error 19 Type or namespace definition, or end-of-file expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 95 10 CreateDatabase

      Error 20 ) expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 27 81 CreateDatabase

      Error 21 ; expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 27 81 CreateDatabase

      Error 22 ; expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 28 32 CreateDatabase

      Error 23 ; expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 28 35 CreateDatabase

      Error 24 ; expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 30 14 CreateDatabase

      Error 25 Expected ; or = (cannot specify constructor arguments in declaration) F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 31 22 CreateDatabase

      Error 26 Invalid expression term '[' F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 31 23 CreateDatabase

      Error 27 ) expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 31 24 CreateDatabase

      Error 28 ; expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 31 33 CreateDatabase

      Error 29 Invalid expression term ']' F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 31 33 CreateDatabase

      Error 30 ; expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 31 35 CreateDatabase

      Error 31 ; expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 31 42 CreateDatabase

      Error 32 Invalid expression term ',' F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 31 42 CreateDatabase

      Error 33 ; expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 31 58 CreateDatabase

      Error 34 ; expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 31 66 CreateDatabase

      Error 35 Invalid expression term ',' F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 31 66 CreateDatabase

      Error 36 ; expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 31 77 CreateDatabase

      Error 37 ; expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 32 10 CreateDatabase

      Error 38 Invalid expression term ')' F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 32 10 CreateDatabase

      Error 39 ; expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 32 11 CreateDatabase

      Error 40 ; expected F:\4th SEM\CreateDatabase\CreateDatabase\Form1.cs 32 13 CreateDatabase

    • profile image

      amrit 

      6 years ago

      abe chalta nahi hai!!!!!!!!!!!!

    • profile image

      sagar maiyad 

      6 years ago

      i cant open connection..

      error:

      Server Error in '/database' Application.

      Could not find installable ISAM.

      Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

      Exception Details: System.Data.OleDb.OleDbException: Could not find installable ISAM.

      Source Error:

      Line 46:

      Line 47:

      Line 48: Con.Open();

      Line 49:

      Line 50: objCmd = new OleDbCommand(SQL,

    • profile image

      chandan 

      6 years ago

      public void StoreData(byte[] content)

      //Compilation Error in this line....

      Error 1 'StoreData': member names cannot be the same as their enclosing type E:\Chandan\MSAccessStoreImage\WindowsFormsApplication1\WindowsFormsApplication1\StoreData.cs 68 21 WindowsFormsApplication1

    • profile image

      suborno 

      6 years ago

      thanks a lot.can u send me.

    • profile image

      Tester 

      7 years ago

      Don't work!

      Error: Cannot find/open "c:\MyAccessDB"!!!

      So, if the file MyAccessDB not exist, it must be create first, and then open and put the StudentName and picture! Thanx anyway! [sorry for my english :)]!

    • sambaran08 profile image

      sambaran08 

      7 years ago from India

      Nice blog,for any help about C# visit bloging,visit my blog https://hubpages.com/technology/Cnet

      and follow me

    • profile image

      Palani 

      7 years ago

      Very Useful Solution! Breaking my head for the past 4 hrs.

    • mbip profile imageAUTHOR

      mbip 

      8 years ago

      Give me some time.

    • profile image

      shweta 

      8 years ago

      it works well...can i get the code for retrieving data from Access using Generics

    • mbip profile imageAUTHOR

      mbip 

      8 years ago

      Yes, u r right. I'll update it. Thanks again

    • profile image

      Khalid Elboushy 

      8 years ago

      It is V.Good And very Faster in saving data

      but we need to add Namespace System.IO

      using System.IO;

    • profile image

      Narendra 

      8 years ago

      Thanx

      Its Working fine

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)