Saturday, November 20, 2010

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

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.

No comments:

Post a Comment