Click here to Skip to main content
Licence CPOL
First Posted 2 Mar 2008
Views 142,965
Downloads 5,265
Bookmarked 97 times

Simple Movie Database in C# using Microsoft Access

By Ivan Svogor | 28 Mar 2008
Simple database project, C# frontend for Microsoft Access movie database
 
Part of The SQL Zone sponsored by
See Also
3 votes, 6.7%
1
2 votes, 4.4%
2
1 vote, 2.2%
3
9 votes, 20.0%
4
30 votes, 66.7%
5
4.30/5 - 45 votes
3 removed
μ 4.00, σa 2.07 [?]
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)

About the Author

Ivan Svogor



Croatia Croatia

Member
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 | :) ...

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 PinmemberNeptuneHACK!23:39 18 Jan '12  
GeneralMy vote of 5 PinmemberOmarGW2:23 7 Jan '12  
QuestionConnecting the database Pinmembermacantony10:28 2 Jan '12  
AnswerRe: Connecting the database Pinmembermacantony3:58 24 Jan '12  
GeneralMy vote of 5 Pinmembermacantony10:25 2 Jan '12  
GeneralThis is really Helpful PinmemberTharindu Edirisinghe5:42 18 Dec '11  
GeneralMy vote of 5 PinmemberSelectStarFromSky20:49 12 Sep '11  
GeneralMy vote of 5 PinmemberRAJI @Codeproject20:45 9 Sep '11  
QuestionWork Pinmembertdgitchell10:10 9 Sep '11  
Questiongreat job PinmemberVu Minh Khiem0:40 19 Jul '11  
QuestionOLEDB Error FIX PinmemberBobbydoo818:48 14 Jul '11  
Generalthnx Pinmemberbhushanbhoyare20:33 28 May '11  
Generalthanks PinmemberRazibul Islam22:47 18 Jan '11  
GeneralMy vote of 4 PinmemberRazibul Islam22:43 18 Jan '11  
GeneralThank You.. Pinmemberfiyan22207:51 10 Jan '11  
GeneralMy vote of 5 Pinmembersusindhran22:56 6 Oct '10  
Generalsearch Pinmemberhamidhkhhkh12:13 10 Jun '10  
GeneralNeed Help: GridView control problem PinmemberPurish Dwivedi23:50 28 Oct '09  
GeneralThanks Pinmemberwasimmn15:33 9 Sep '09  
Generalcontent combobox Pinmemberguidoursus5:24 27 Jul '09  
GeneralExcellent Pinmemberwtkm7:20 2 Jul '09  
Generalvery useful ! PinmemberHieroma12:56 13 Jan '09  
thx for this project !
 
however I just want to know a little thing : when I edit a movie in the 2nd Form, I want that the dataGridView in the first Form updates automatically (without clicking every time the button "refresh")
 
for that, I added this code just before the MessageBox but without success :
 
string queryString = "SELECT movieID, Title, Publisher, Previewed, MovieYear, Type FROM movie,movieType WHERE movietype.typeID = movie.typeID";
f1.loadDataGrid(queryString);
f1.dataGridView1.Update();

QuestionSelecting Items. Pinmemberkoen-sjohn15:16 7 Jan '09  
Generalthanks a million Pinmembercalvin12068:14 15 Dec '08  
QuestionC# with simple Access tables Pinmemberrana radaideh8:27 23 Nov '08  

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.

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