Click here to Skip to main content
11,478,902 members (65,279 online)
Click here to Skip to main content

Simple Movie Database in C# using Microsoft Access

, 28 Mar 2008 CPOL 235.1K 18.8K 121
Rate this:
Please Sign up or sign in to vote.
Simple database project, C# frontend for Microsoft Access movie database
app.gif

Introduction

For a while now, I'm a member of CodeProject family, and I've never contributed any of my projects. Since this site has been very helpful for me while learning C#, I've decided to share my first project in C#. It was written about a year ago when I joined here. Anyhow, this article is about a simple database built in Microsoft Access and C#. I wanted to explore this because the end user doesn't need to install any SQL servers, he just needs executable binary and *.mdb file. As I mentioned, it is one of my first projects, so it is not very advanced, but the provided code snippets are useful, i.e. connecting to *.mdb file, read/write data, using dataGridView control, adding buttons to cells, etc.

Using the Code

First, you need to create a database in Microsoft Access. The database is very simple and therefore, there is a lot of scope for future work and improvement.

//  First table contains movies
//  where movieID is auto-increment value, also primary key, and typeID foreign key
//  movies (movieID, Title, Publisher, Previewed, Year, typeID) 
//  --------------------------------------------------------------- 
//  Second table contains movie types
//  movietypes (typeID, Type)

If you have a bigger database in your mind, you can use some generator to create the database. For a small project like this, those kinds of tools aren't necessary (also, try to keep it in 3NF).

Ok, now we have our database. Microsoft Access allows us to add records, but we want to create our own front end. To be able to connect to the database and manipulate with records, it is necessary to use the System.Data.OleDb namespace which will provide the required methods.

In the constructor of the initial form, the application connects to the database using the following code:

public Form1()
{
    InitializeComponent();
    // initiate DB connection
    string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;
        Data Source=moviedb.mdb";
    try
    {
        database = new OleDbConnection(connectionString);
        database.Open();
        //SQL query to list movies
        string queryString = "SELECT movieID, Title, 
            Publisher, Previewed, Year, Type 
            FROM movie,movieType WHERE movietype.typeID = movie.typeID";
        loadDataGrid(queryString);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        return;
    }
}

The method loadDataGrid loads the data from the database to the dataGridView control, using the SQL query in the string variable, queryString. Here is the implementation:

public void loadDataGrid(string sqlQueryString) {

            OleDbCommand SQLQuery = new OleDbCommand();
            DataTable data = null;
            dataGridView1.DataSource = null;
            SQLQuery.Connection = null;
            OleDbDataAdapter dataAdapter = null;
            dataGridView1.Columns.Clear(); // <-- clear columns

            SQLQuery.CommandText = sqlQueryString;
            SQLQuery.Connection = database;
            data = new DataTable();
            dataAdapter = new OleDbDataAdapter(SQLQuery);
            dataAdapter.Fill(data);
            dataGridView1.DataSource = data;

            dataGridView1.AllowUserToAddRows = false; // <-- remove the null line
            dataGridView1.ReadOnly = true;          // <-- so the user cannot type 

            // following code defines column sizes
            dataGridView1.Columns[0].Visible = false; 
            dataGridView1.Columns[1].Width = 340;
            dataGridView1.Columns[3].Width = 55;
            dataGridView1.Columns[4].Width = 50;
            dataGridView1.Columns[5].Width = 80;

            // insert edit button into datagridview
            editButton = new DataGridViewButtonColumn();
            editButton.HeaderText = "Edit";
            editButton.Text = "Edit";
            editButton.UseColumnTextForButtonValue = true;
            editButton.Width = 80;
            dataGridView1.Columns.Add(editButton);

            // insert delete button to datagridview
            deleteButton = new DataGridViewButtonColumn();
            deleteButton.HeaderText = "Delete";
            deleteButton.Text = "Delete";
            deleteButton.UseColumnTextForButtonValue = true;
            deleteButton.Width = 80;
            dataGridView1.Columns.Add(deleteButton);
        }

The interesting part of this code is adding buttons to dataGridView cells. Using these buttons, you can update or delete the selected row. The other way to do this is to place only two buttons outside the dataGridView control, and then select the row you want to edit/delete and press the button. Here, every row has its own buttons.

The question remains, how can I detect when the button is pressed, and where do I place my code to do some action. Well, here is the way to do it:

private void dataGridView1_CellContentClick
    (object sender, DataGridViewCellEventArgs e)
{
    string queryString = "SELECT movieID, Title, Publisher, 
        Previewed, Year, Type 
        FROM movie, movieType WHERE movietype.typeID = movie.typeID";
    
    int currentRow = int.Parse(e.RowIndex.ToString());
    try
    {
        string movieIDString = dataGridView1[0, currentRow].Value.ToString();
        movieIDInt = int.Parse(movieIDString);
    }
    catch (Exception ex) { }
    // edit button
    if (dataGridView1.Columns[e.ColumnIndex] == editButton && currentRow >= 0)
    {
        string title = dataGridView1[1, currentRow].Value.ToString();
        string publisher = dataGridView1[2, currentRow].Value.ToString();
        string previewed = dataGridView1[3, currentRow].Value.ToString();
        string year = dataGridView1[4, currentRow].Value.ToString();
        string type = dataGridView1[5, currentRow].Value.ToString();
                    
        Form2 f2 = new Form2();
        f2.title = title;
        f2.publisher = publisher;
        f2.previewed = previewed;
        f2.year = year;
        f2.type  = type;
        f2.movieID = movieIDInt;
        f2.Show();
        dataGridView1.Update();
    }
... 

I used the CellContentClick event. So now, when the button is down, I need to know the selected row. I do this by using the e.RowIndex. Using this variable, you can fetch any column value of the selected row. As shown, the first parameter is column index, and the second is row index. When the update of the selected row is completed in Form2, now using the Update() method on the dataGridView1 object, you can see the changes that were made.

The delete button works the same way.

// delete button
else if (dataGridView1.Columns[e.ColumnIndex] == 
deleteButton && currentRow >= 0)
{
    // delete SQL query
    string queryDeleteString = 
        "DELETE FROM movie WHERE movieID = "+movieIDInt+"";
    OleDbCommand sqlDelete = new OleDbCommand();
    sqlDelete.CommandText = queryDeleteString;
    sqlDelete.Connection = database;
    sqlDelete.ExecuteNonQuery();
    loadDataGrid(queryString);
}

Conclusion

This project shows a simple way how to use Microsoft Access database and .NET controls to display stored data. Everything that you need to start your own more advanced application for a similar purpose is shown here. The project is for C# beginners, and with a little bit of imagination, it can be improved and useful. Hope you like it. Cheers!!

History

  • 28.3.2008 - Insertion bug fixed, added SelectionMode property to dataGridView1

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ivan Svogor

Croatia Croatia
Ivan Svogor, is a final year graduate student of Information and Software Engineering at university of Zagreb, Croatia. His interests is SOA, human computer interaction, computer & embedded systems (sensors) integration, basically he likes cool stuff Smile | :) ...

Comments and Discussions

 
QuestionCellContentClick event Pin
Member 1094815319-Jan-15 9:57
memberMember 1094815319-Jan-15 9:57 
Answervery helpfull Pin
Member 1114545611-Oct-14 1:26
memberMember 1114545611-Oct-14 1:26 
GeneralMy vote of 5 Pin
popernik26-Apr-13 0:52
memberpopernik26-Apr-13 0:52 
QuestionProblem with Pin
rathinkishan16-Mar-13 7:16
memberrathinkishan16-Mar-13 7:16 
AnswerRe: Thanks Pin
rizwankhan0072-Jun-13 1:22
memberrizwankhan0072-Jun-13 1:22 
GeneralMy vote of 5 Pin
Member 960783717-Nov-12 11:54
memberMember 960783717-Nov-12 11:54 
QuestionChange design Pin
Jarrod_Williams30-Sep-12 0:17
memberJarrod_Williams30-Sep-12 0:17 
Questiondatabase problem Pin
eriktheleon5-Jul-12 14:01
membereriktheleon5-Jul-12 14:01 
Questionwell done Pin
sofiaaa25-Jun-12 23:22
membersofiaaa25-Jun-12 23:22 
GeneralMy vote of 5 Pin
DanilS2-May-12 11:02
memberDanilS2-May-12 11:02 
GeneralMy vote of 5 Pin
NeptuneHACK!18-Jan-12 23:39
memberNeptuneHACK!18-Jan-12 23:39 
GeneralMy vote of 5 Pin
OmarGW7-Jan-12 2:23
memberOmarGW7-Jan-12 2:23 
QuestionConnecting the database Pin
macantony2-Jan-12 10:28
membermacantony2-Jan-12 10:28 
AnswerRe: Connecting the database Pin
macantony24-Jan-12 3:58
membermacantony24-Jan-12 3:58 
GeneralRe: Connecting the database Pin
sabichos6-Mar-12 5:34
membersabichos6-Mar-12 5:34 
GeneralMy vote of 5 Pin
macantony2-Jan-12 10:25
membermacantony2-Jan-12 10:25 
GeneralThis is really Helpful Pin
Tharindu Edirisinghe18-Dec-11 5:42
memberTharindu Edirisinghe18-Dec-11 5:42 
GeneralMy vote of 5 Pin
SelectStarFromSky12-Sep-11 20:49
memberSelectStarFromSky12-Sep-11 20:49 
GeneralMy vote of 5 Pin
RAJI @Codeproject9-Sep-11 20:45
memberRAJI @Codeproject9-Sep-11 20:45 
QuestionWork Pin
tdgitchell9-Sep-11 10:10
membertdgitchell9-Sep-11 10:10 
Questiongreat job Pin
Vu Minh Khiem19-Jul-11 0:40
memberVu Minh Khiem19-Jul-11 0:40 
QuestionOLEDB Error FIX Pin
Bobbydoo814-Jul-11 18:48
memberBobbydoo814-Jul-11 18:48 
Generalthnx Pin
bhushanbhoyare28-May-11 20:33
memberbhushanbhoyare28-May-11 20:33 
Generalthanks Pin
Razibul Islam18-Jan-11 22:47
memberRazibul Islam18-Jan-11 22:47 
GeneralMy vote of 4 Pin
Razibul Islam18-Jan-11 22:43
memberRazibul Islam18-Jan-11 22:43 
GeneralThank You.. Pin
fiyan222010-Jan-11 7:51
memberfiyan222010-Jan-11 7:51 
GeneralMy vote of 5 Pin
susindhran6-Oct-10 22:56
membersusindhran6-Oct-10 22:56 
Generalsearch Pin
hamidhkhhkh10-Jun-10 12:13
memberhamidhkhhkh10-Jun-10 12:13 
GeneralNeed Help: GridView control problem Pin
Purish Dwivedi28-Oct-09 23:50
memberPurish Dwivedi28-Oct-09 23:50 
GeneralThanks Pin
wasimmn9-Sep-09 15:33
memberwasimmn9-Sep-09 15:33 
Generalcontent combobox Pin
guidoursus27-Jul-09 5:24
memberguidoursus27-Jul-09 5:24 
GeneralExcellent Pin
wtkm2-Jul-09 7:20
memberwtkm2-Jul-09 7:20 
Generalvery useful ! Pin
Hieroma13-Jan-09 12:56
memberHieroma13-Jan-09 12:56 
QuestionSelecting Items. Pin
koen-sjohn7-Jan-09 15:16
memberkoen-sjohn7-Jan-09 15:16 
Generalthanks a million Pin
calvin120615-Dec-08 8:14
membercalvin120615-Dec-08 8:14 
QuestionC# with simple Access tables Pin
rana radaideh23-Nov-08 8:27
memberrana radaideh23-Nov-08 8:27 
AnswerRe: C# with simple Access tables Pin
Ivan Svogor23-Nov-08 8:58
memberIvan Svogor23-Nov-08 8:58 
GeneralGreat Example Thanks - Question Pin
tracam23-Oct-08 13:30
membertracam23-Oct-08 13:30 
GeneralRe: Great Example Thanks - Question Pin
Ivan Svogor23-Nov-08 8:57
memberIvan Svogor23-Nov-08 8:57 
QuestionClose Form1 Class? Pin
MeistahLampe10-Jun-08 12:28
memberMeistahLampe10-Jun-08 12:28 
AnswerRe: Close Form1 Class? Pin
Ivan Svogor23-Nov-08 8:55
memberIvan Svogor23-Nov-08 8:55 
GeneralOnline Pin
noughtica15-May-08 18:54
membernoughtica15-May-08 18:54 
GeneralThanks Pin
Jan Boer4-Apr-08 4:13
memberJan Boer4-Apr-08 4:13 
GeneralRe: Thanks Pin
Ivan Svogor4-Apr-08 7:48
memberIvan Svogor4-Apr-08 7:48 
GeneralRe: Thanks Pin
Jan Boer14-Apr-08 4:06
memberJan Boer14-Apr-08 4:06 
Generalrefresh datagridview Pin
Member 6706853-Apr-08 12:35
memberMember 6706853-Apr-08 12:35 
GeneralRe: refresh datagridview Pin
Member 6706853-Apr-08 13:05
memberMember 6706853-Apr-08 13:05 
GeneralRe: refresh datagridview Pin
Ivan Svogor4-Apr-08 7:49
memberIvan Svogor4-Apr-08 7:49 
Generalthank you Pin
HayLin25-Mar-08 8:55
memberHayLin25-Mar-08 8:55 
GeneralRe: thank you Pin
Ivan Svogor25-Mar-08 9:28
memberIvan Svogor25-Mar-08 9:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150520.1 | Last Updated 28 Mar 2008
Article Copyright 2008 by Ivan Svogor
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid