Bind GridView Control at Runtime

There are times when you don’t want to configure the GridView’s control DataSource property to point to some build in types of  data sources, such as EntityDataSource or SqlDataSource. You know though and have access to what kind of data class will the GridView control be bind. For example, maybe you expect results come from a WCF webservice, and you know that several items of type “Review” are expected to be retrieved. There is a simple way follow, showing how to bind a list of Items of type “Review” to the GridView control.

First of all open Visual Studio 2012, and create a new ASP.NET empty website (C# template).

Create empty Website

Create empty Website

Right click on the website project and select Add -> new ASP.NET folder -> App.Code. Right click the new created folder and add a new item. In the new item window, select a C# class file, named Review.cs. Right click again on the website project and add a new Item again. This time select a new web form from C# template. You can name your new aspx page as you want. Your solution structure should look like this now.

Untitled2

Write the code for the Review class. Simply add few properties and at the end include the class in a namespace called Model.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Model
{
public class Review
{

public int ID { get; set; }
public string Title { get; set; }
public string VideoUrl { get; set; }
public Review() {}

public Review(int id, string title, string video)
{
ID = id;
Title = title;
VideoUrl = video;
}
}
}

Open the Default.aspx page in source mode. Drag and drop from toolbox a GridView. From GridView’s SmartTag you can choose a style to format the colors of the GridView. I chose Professional for this example.Inside “asp:GridView” tag add the following two attributes:

 AutoGenerateColumns="false" ItemType="Model.Review" 

. Your GridView code should look like this at the moment.


<div>













</div>

Configure Default.aspx.cs file, to bind the GridView Control to a list of Review Items. To do this, i created a sample function which generates mock Review data. Later, in the Load event of the Page, configure the DataSource property of the GridView to point the mock data. In order to do create the Load event, in case it doesn’t exist already, simply double click in design mode of the Default.aspx file. In the end don’t forget to call the DataBind() function of the GridView control. Otherwise, it wont bind the requested data. Review.cs file should look like this.

using Model;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List reviews = getSampleReviews();

        GridView1.DataSource = reviews;
        GridView1.DataBind();
    }

    private static List getSampleReviews()
    {
        List reviews = new List();
        reviews.Add(
            new Review
            {
                ID = 1,
                Title = "Assassin's Creed",
                VideoUrl = "http://www.youtube.com/embed/-pUhraVG7Ow?html5=1"
            }
            );
        reviews.Add(
            new Review
            {
                ID = 2,
                Title = "Age of Empires",
                VideoUrl = "http://www.youtube.com/embed/K6kkvpkgUYQ?html5=1"
            }
            );
        reviews.Add(
            new Review
            {
                ID = 3,
                Title = "Pro Evolution Soccer 2013",
                VideoUrl = "http://www.youtube.com/embed/5OiPNNicjUQ?html5=1"
            }
            );
        return reviews;
    }
}

The last thing you must make is configure what kind of data you want your GridView control to show. In the Default.aspx file, switch to source view and after the “asp:GridView” tag, create a Columns tag. Don’t forget to close it. Inside the Columns tags, we are going to create 3 Template Fields where the three fields of every Review record bound, will be displayed. For every template field will add a ItemTemplate at the moment. We could add also EditItemTemplate or InsertItemTemplate but we ll see how this work in other post. In the first two ItemTemplates add a asp:Label control and set the Text property to

Text="">

and

Text=""

respectively. This will bind the ID and Title properties of every Review record. In the last ItemTemplate add a simple anchor (link) just like that:

&lt;a href=&quot;" target="_blank"&gt;Watch</a>

Your GridView code (style code omitted) should look like this:





&lt;asp:Label ID=&quot;lblReviewId&quot; runat=&quot;server&quot; Text=&quot;"&gt;




&lt;asp:Label ID=&quot;lblReviewTitle&quot; runat=&quot;server&quot; Text=&quot;"&gt;




&lt;a href=&quot;" target="_blank"&gt;Watch</a>




        

Just build your website and open it with your favorite browser. The result will be this. You can click at the watch link of every record, this should open a new window which will point to the YouTube’s video url. Enjoy!

grid

Advertisements


Categories: ASP.NET

Tags: ,

2 replies

  1. This piece of writing offers clear idea for the new
    visitors of blogging, that actually how to do blogging.

Trackbacks

  1. Edit GridView control using an SqlDataSource and Template fields in ASP.NET 4.5 | chsakell's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: