ASP.NET Web Pages - Connecting to the Database

For this sample application, I have used Visual Studio 2012 RC, ASP.Net Web Page2 Beta and .Net 4.5 framework RC.

Step 1

To learn more about the basics of ASP.Net web pages, please refer to my previous blog:

Step 2

Add a new page in the ASP.Net web pages demo project.

Image 1.jpg

Step 3

Add the "student" connectiion string in the existing web.config file.

 Image 2.jpg

    <add name="StarterSite" connectionString="Data Source=|DataDirectory|\StarterSite.sdf" providerName="System.Data.SqlServerCe.4.0" />
    <add name="student" connectionString ="Server=(local);Database=student;Trusted_Connection=True;"
         providerName="System.Data.SqlClient" />

Step 4

Add the following code to get the data from the student database.

            var db = Database.Open("student"); //Open the database here
            var selectedData = db.Query("SELECT * FROM student"); //get the data from student table
            var grid = new WebGrid(source: selectedData); //set the data source to the data grid

 Image 3.jpg

Step 5

Fill in the datagrid with the data.


Step 6

Hit F5 to run the application.

 Image 4.jpg

Step 7

Applying styles to the WebGrid.

Add the following style information in the head section.

            <style type="text/css">
               .grid { margin: 4px; border-collapse: collapse; width: 600px; font-family:Calibri; }
               .grid th, .grid td { border: 1px solid #C0C0C0; padding: 5px; }
               .head {  background-color:Gray;  font-weight: bold; color: black; }
               .alt { background-color: #E8E8E8; color: #000; }

Step 8

Add the style information to the webgrid. 

                        tableStyle: "grid",
                        headerStyle: "head",
                        alternatingRowStyle: "alt",

Image 5.jpg

Step 9

Custom paging

var grid = new WebGrid(source: selectedData,rowsPerPage:5);

Image 6.jpg

Hit F5 to run the application.
Image 7.jpg

Up Next
    Ebook Download
    View all
    View all