Here's a two for one. In this post, I'll show you how to use the SPGridView to display data from a list and I'll also show you how to setup an update panel to refresh the data displayed in the grid every 10 seconds. This webpart will require 3 references.
- Microsoft.SharePoint - for the SPGridView control
- System.Web - for overriding the CreateChildControls method
- System.Web.Extensions - for the UpdatePanel
The first thing you'll want to do is override the OnInit event. In here, you'll want to check for an existing ScriptManager. If it doesn't exist, add it.
NOTE: The ScriptManger is required to be on the page if you want to use the UpdatePanel and there can only be one ScriptManager per page, which is why we do the check.

Now we move on to the CreateChildControls method. First, we need to get our list. In this example I'm hardcoding this. You'll also instantiate the SPGridView and set the AutoGenerateColumns property to false. (We're only going to display a few columns from the list, so we'll specify those columns in the code.)

Next, we're going to create a few SPBoundFields and add them to the grid. The HeaderText is the title that appears in the column and DataField is the list's field name. Nothing special here.

Now we need to create an SPDataSource object. This is used to provide a source to the grid.DataSource property. Once we assign the list to the SPDataSource.List, we can go ahead and provide to source to the grid and bind the data.

Here comes the cool (but still simple) stuff. We're going to create a timer. The timer is going to trigger the UpdatePanel to update its content. As you can see in the image, I'm setting the timer's interval to 10000 (10000 = 10 seconds). Now, on to the updatePanel. Once instantiated, set the UpdateMode. Your options are Conditional or Always. We're going to use always here. Add your updatePanel to the page by using the Controls.Add method. Then add your grid and timer to the ContentTemplateContainer.

The following image will show you what an SPGridView will look like when on a page. As you can see, it uses the css used by the lists and libraries giving you that SharePoint look without having to do it yourself. Also, since the control is wrapped in an updatePanel, every 10 seconds, the updatePanel's content is refreshed and if I have a new item or remove an item, the changes will be reflected in the grid.

Labels: Developer