C# – Datagrid View – C# connect application to DB in Visual Studio

Today I was looking a bit over SQL Server and Visual Studio and I have somehow liked the nice cooperation between these two. Thus, I have come up with the idea to build a simple application, just to demonstrate how to connect db to app in Visual Studio. Nothing fancy, even the CRUD is not implemented. Something like this:

scr03

We have a datagrid view, getting and displaying information from the DB. Then we have a few labels, which give information for each line of the database, based on Next and Previous. That’s all. Let’s start.

First the DB – this is the sql code for the beautiful table:

Once the table was generated, from Visual Studio I have selected a new Windows Application. Then I simply added DataGridView from the toolbox. In the DataGridView, there is a nice way to bind a db, using the small arrow in the top. Then selecting a db and clicking next:

scr01

The Server name is actually a must – Windows could not find mine localhost, so I had to copy and paste it – as you see (localdb)\MSSQLLocalDB. The rest was quite easy – just clicking next.

scr02

 

Once the dataset was ready, I was able to view it in the DataGridView just by running Ctrl+F5. But I wanted to have a little more fancy application – thus I have started to build a few labels and buttons, showing the various db entries.

And then the coding started – pretty much, on the loading of the application I read the database and save its data into a few public list variables. Then I simply read data from these variables, whenever the buttons “Next” and “Previous” are touched. That’s the short story. The long story is here:

There are some repetitions in the code and places where I could have followed better syntax or etc., but the idea of the article is to show how to connect DB to C# app and nothing more. 🙂

Here is the whole project in GitHub.Com.

About

VBA Developer

Tagged with: ,