Click here to Skip to main content
Email Password   helpLost your password?
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

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralNeed Help: GridView control problem
Purish Dwivedi
23:50 28 Oct '09  
I have created my webapp in ASP.NET, C# and MS-Access.
in Table I have cell value as, 1 and 0. At the time of binding I want to convert it to On and Off respecively. How can I do it? Please help , as I am new to .NET
This is my code.

private void Binding()
{
// create the connection
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:/GmoteDeviceControl/App_Data/DeviceCtrl.mdb;User Id=admin;Password=;");

// Open the connection
con.Open();

// create the DataSet
DataSet ds = new DataSet();

// create the adapter and fill the DataSet
OleDbDataAdapter da = new OleDbDataAdapter("Select DEVICE_NAME,CURRENT_STATE from SUBSCRIBER_DEVICES", con);
da.Fill(ds);



//Binding DataSource with GridView
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();

// close the connection
con.Close();
}


Thank You.
GeneralThanks
wasimmn
15:33 9 Sep '09  
Thanks
Generalcontent combobox
guidoursus
5:24 27 Jul '09  
Hello
I find your database and now I understand more about C#.
But why do you put your values in the code under combobox1 and combobox2 while this values are in the MsAccess database (table movietype)?

Verhoeven Guido
GeneralExcellent
wtkm
7:20 2 Jul '09  
Thanks for the great work.
Generalvery useful !
Hieroma
12: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.
koen-sjohn
15:16 7 Jan '09  
Hi There,
First of all I'd to thank you for this project. It Helped me start programming in C.
As I'm fairly new in C, I have a question.
I tried to a a rating form into this great program, but now I'm stuck.
I don't have a clue to solve it, and after a few hours it is getting me nuts.
I did create a third form, in which i need the ID of the movie. And I also made an other table which is called rating and the ID's correspondending to the Movie ID should be shown in the datagrid. But nothing shows up.
Here is the snipped which I included in Form1.

else if (dataGridView1.Columns[e.ColumnIndex] == ratingButton && currentRow >= 0)
{
string title = dataGridView1[1, currentRow].Value.ToString();
//runs form 2 for editing
Form3 f3 = new Form3();
f3.title = title;
f3.movieID = movieIDInt;
f3.Show();
dataGridView1.Update();

}
Then in Form 3 I'd put this code in:
            try
{
database = new OleDbConnection(connectionString);
database.Open();
//SQL query to list ratings
string queryString = "SELECT ID, Naam, Rate, Comment FROM rating where ID LIKE "+movieID+"";
loadDataGrid(queryString);
}
Somehow the movieID returns 0 in this query.
But when I show the query on my screen like this:
        private void Form3_Load(object sender, EventArgs e)
{
string queryString = "SELECT ID, Naam, Rate, Comment FROM rating where ID LIKE '" + movieID + "'";
label1.Text = queryString;
}
It returns the correct ID number.

Why doesn't this work in the real SQLquery?
I think it has something to do with movieID being an Integer?
I don't quite understand how this works yet.
I would be very pleased if someone helps me.
Greetings from holland,
Koen
Generalthanks a million
calvin1206
8:14 15 Dec '08  
thanks a million i got saved caz of u
QuestionC# with simple Access tables
rana radaideh
8:27 23 Nov '08  
Confused how i can simply join C# with tables in access and how i can only read from it and take some values?

rannosh
AnswerRe: C# with simple Access tables
Ivan Svogor
8:58 23 Nov '08  
Sorry, I don't understand your question. Can you be more precise?

Free the mallocs!!

GeneralGreat Example Thanks - Question
tracam
13:30 23 Oct '08  
I have tried to add 2 buutons to a datadridview object in similar fashion to the example. My project has 5 columns loaded from an access database and the two buttons are added to the right hand end of the table so it looks fine.
But first time the datagridview is loaded, the button indexes in the datagridview are 0 and 1 and every time after that they are 6 and 7.

I downloaded your example and changed the page order in the tabcontrol to the Search/Edit Database tab is shown first and the same thing happens

Any ideas wwhy?

Thanks/Regards
GeneralRe: Great Example Thanks - Question
Ivan Svogor
8:57 23 Nov '08  
You can check in the order of creation..

Free the mallocs!!

GeneralClose Form1 Class?
MeistahLampe
12:28 10 Jun '08  
Hi,

first of all, i really like you work, helped me a lot to figure out how the oledb namespace works ^^

but, wouldn’t it be necessary to close the form1 class after using it at the event of the updatebutton in form2? ….else you got hundreds of objects of that class after a while of using this program.
GeneralRe: Close Form1 Class?
Ivan Svogor
8:55 23 Nov '08  
Sure! But, this is from beginners section, no there is no point to bother beginners with stuff like that. This is just the door, when you walk trough them, you can see what's in and make it better.
I intentionally left out some parts. There is a lot of optimization left Smile

Free the mallocs!!

GeneralOnline
noughtica
18:54 15 May '08  
How can you turn this into an web movie database with ASP.net?
GeneralThanks
Jan Boer
4:13 4 Apr '08  
Hey

This database helped me learn database use easily since it is simple and quick to understand with optimal efficientcy for beginners. Thank you for the help! Big Grin
GeneralRe: Thanks
Ivan Svogor
7:48 4 Apr '08  
Hello, yeah, the hole idea about this simple project is to help beginners catch up with databases. If I used MSSQL server and more advanced approach it wouldn't be very useful because people who read advanced articles, certainly know how to do this. So I'm trying to resolve the target audience Smile

Free the mallocs!!

GeneralRe: Thanks
Jan Boer
4:06 14 Apr '08  
For MSAccess 07, Use the following Connection Sting
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= ..." This prevents the format error being invoked Smile
Generalrefresh datagridview
Member 670685
12:35 3 Apr '08  
Good evening,i have download your program,so, when I update any movie data and I click on the msgbox,the grid does not show me the last update...,the new value does not apper into the grid....to see it I have to click on the tab "Add new movie" and after click on "Search/edit database".What can I do to see the update data immediately (when the Form2 is closed)?

Thank a lot
Paolo
GeneralRe: refresh datagridview
Member 670685
13:05 3 Apr '08  
Hello!!
Prolem solved....
I have change the line:
f2.Show();

in:

f2.ShowDialog();
queryString = "SELECT movieID, Title........
loadDataGrid(queryString);
dataGridView1.Update();



Thanks
Paolo
GeneralRe: refresh datagridview
Ivan Svogor
7:49 4 Apr '08  
Yes.. you already got it, you need to actualize dataGridView content, so simply refresh it Smile

Regards

Ivan

Free the mallocs!!

Generalthank you
HayLin
8:55 25 Mar '08  
I would just like to thank you for making this project, this was just the thing i was looking for, because i'm a c# beginner Smile

PS; didn't know you are Croatian , i'm Slovenian ... hvala
GeneralRe: thank you
Ivan Svogor
9:28 25 Mar '08  
nema problema Smile

Sorry all for the inconvenience caused by the insertion bug. I'm currently a bit busy, but I'll try to fix it by the end of the week.

Regards,

I.Š.

Free the mallocs!!

GeneralRe: thank you
Chanaka Ishara
5:24 27 Mar '08  
yeah i got that bug too. i can't enter or edit any data entry. please correct it Smile Smile Smile Smile

Chanaka Ishara

GeneralRe: thank you [modified]
Ivan Svogor
12:17 28 Mar '08  
Hello again

So I've fixed this minor bug. The problem was in the attribute name Year, this name is already used by system so it caused exception problems. Now I've named that variable MovieYear and seems to work fine, also this query trouble maker is added to try-catch block.

Thank you all for reporting this error.

Cheers!


P.S.
As soon as I catch some break, I'll add new project online...

Free the mallocs!!
modified on Friday, March 28, 2008 5:24 PM

Generalhelp ur project is not working
Chanaka Ishara
7:37 22 Mar '08  
when i try to add information to data base it shows a error in INSERT INTO part. if you can solve that problem this is a very good project Wink Wink

Chanaka Ishara


Last Updated 28 Mar 2008 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010