Now that we’ve learned how to map a persistent database onto classes and objects in our code, let’s look at how we can display that data in a grid-like formatting of the table data we're retrieving from our “ database. For this purpose, we're going to use the GridView Server Control which has a feature called “Data Binding.” Data Binding is just baked-in logic for certain Server Controls, in ASP.NET, that allows you to give it a data source – in this case, a collection of customer objects. And it can then work with that collection, retrieve the records, format each individual record as a row in a table, and then display it all to the end user. Ideally, we should separate this “Persistence” layer information into its own project. But for now, it’s important to understand how data can be mapped from a database to local C# objects and then display it using a GridView.
For this lesson, we’re going to use where we left off in the previous lesson as the starting point. Once there, navigate to Toolbox > Data, then drag and drop a GridView Server Control to the Default.aspx:
These Data Controls are non-visual elements that are either Data-Source or Data-Bound Controls. Data-Source Controls ask the question, "Where do I get the data?" Whereas Data-Bound Controls ask, "How do I connect to a database, retrieve information from it and display that data?"
In the Properties Window for this GridView Control, set the programmatic ID to “customerGridView”:
Now, instead of iterating through customers in Default.aspx.cs, let’s assign the contents of customers to customersGridView.DataSource:
Note that, even though customers seems like it would be an array or List<>, it is actually of type DbSet<>, which is a List-like container format for an entire database:
After we have the DataSource, we can then Bind to it by calling the DataBind() method on the object:
If you run the application now, this method will throw an exception:
To fix this, we simply convert customers from a DbSet<> to a List<> by running it through the ToList() method:
Now when you run the application, you will see that the data retrieved from the database seemingly becomes magically bound to the GridView Default.aspx:
Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView