Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attach files to ms access database using c#

Tags:

c#

attachment

I am currently working on a project. A document repository system. I am using C# windows forms and MS Access 2010 as my database. My table for the storing of documents is named "Documents" and has 2 columns namely Project ID and File (Attachment data type). I can now browse files using the openfiledialog but can't seem to upload it.

Here is my current code for my upload button.

        con = new OleDbConnection(cs);
        con.Open();     
        String num = lblPnum.Text.ToString();
        string a = "INSERT INTO [Documents]([ProjectID]) VALUES('"+ num + "')";

        cmd = new OleDbCommand(a);
        cmd.Connection = con;
        cmd.ExecuteReader();
        con.Close();
        MessageBox.Show("Document Successfully Added", "Prompt", MessageBoxButtons.OK, MessageBoxIcon.Information);
        this.Close();
        FrmHome home = new FrmHome();
        home.Show();
        home.statusPanel.Text = statusPanel.Text;

As of the moment, I can already get the project ID based on the project number that I have selected. what do I need to add to be able to attach files to my database and show it to the gridview.

like image 227
Angelo Avatar asked Jul 22 '26 23:07

Angelo


1 Answers

This article on Microsoft Docs has a working example: Work with attachments in DAO

var dbe = new DBEngine();
Database db = dbe.OpenDatabase(DBFilePath, ReadOnly: false);

// first record set is the table
Recordset rs = db.OpenRecordset("SELECT * FROM " + TableName); 
rs.MoveFirst();
rs.Edit(); 

// second record set is the actual field / cell in the table
Recordset2 rs2 = (Recordset2)rs.Fields["Attachments"].Value;

// add document
rs2.AddNew();
Field2 f2 = (Field2)rs2.Fields["FileData"];
f2.LoadFromFile(ImageFile);
rs2.Update();

rs2.Close();
rs.Update();
rs.Close()
like image 141
Charlie P Avatar answered Jul 25 '26 13:07

Charlie P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!