다음을 통해 공유


How to: Create a Basic JS Grid Control

Applies to: SharePoint Foundation 2010

This topic demonstrates how to create a basic, read-only grid by using the JS Grid control and Microsoft Visual Studio 2010.

Note

The basic grid control that you create in this procedure is used as the starting point for procedures in other topics. After you create this grid, see JS Grid Control for links to other topics that show how you can modify it. For example, How to: Create an Editable JS Grid Control shows how you can make the grid editable.

To render the JS Grid control, you must provide some sample data. The sample data is in GridData.cs. The code to parse the data is in the GridUtilities.cs file. Both files are stored in the GridUtils folder. Although the data file and the utilities file are more extensive than you need to create the basic grid, they contain features you use in later topics.

Prerequisites

  • Microsoft SharePoint Foundation 2010

  • Microsoft Visual Studio 2010

  • SharePoint development tools in Microsoft Visual Studio 2010

Note

Although you can complete this procedure without using Visual Studio, it is easier if you use both Visual Studio 2010 and the SharePoint development tools in Visual Studio 2010. Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements.

To create an empty SharePoint project

  1. Start Visual Studio 2010 by using the Run as administrator option.

  2. On the File menu, click New, and then select Project.

  3. In the New Project dialog box, expand the Visual C# node, expand the SharePoint node, and then select the 2010 node.

  4. In the templates pane, select Empty SharePoint Project, name the solution JSGrid, and then click OK. The SharePoint Customization Wizard appears. This wizard enables you to select the site that you use to debug the project and the trust level of the solution.

  5. In the SharePoint Customization Wizard, select Deploy as a farm solution, and then click Finish to accept the default local SharePoint site.

    Note

    Any Web Part must be a farm (fully trusted) solution.

To add a Web Part to the project

  1. In Solution Explorer, right-click the JSGrid project, point to Add, and then select New Item.

  2. In the Add New Item dialog box, expand the SharePoint node, and then select 2010.

  3. In the templates pane, select Visual Web Part, name the item JSGridWebPart, and click Add. The Web Part appears in Solution Explorer. This action generates the library references and, in our example, JSGridWebPart.cs.

    Note

    This example uses a Visual Web Part; the Visual Web Part enables the Design view for the .ascx control, and also enables creating simple Web Part properties without having to create an Editor Part.

To add the JS Grid control

  • To initialize the control, paste the following code into JSGridWebPartUserControl.ascx.

    <SharePoint:JSGrid ID="_grid" runat="server" /> 
    <script type="text/javascript">
        Type.registerNamespace("GridManager");
        GridManager = function () {
            this.Init = function (jsGridControl, initialData, props) {
                var dataSource = new SP.JsGrid.StaticDataSource(initialData);
                var jsGridParams = dataSource.InitJsGridParams();
    
                jsGridParams.styleManager.RegisterCellStyle('TextRightAlign', SP.JsGrid.Style.CreateStyle(SP.JsGrid.Style.Type.Cell, { textAlign: 'right' }));
                jsGridControl.Init(jsGridParams);
            }
        };
    </script>
    

    The first line describes the JS Grid control. The script in the following lines registers the grid manager, registers the data source, registers a right alignment style, and handles the initialization tasks.

Note

When adding a Web Part to a SharePoint 2010 page, Web Parts are displayed in groups. The group in which a Web Part is displayed is controlled by the Property element in the Elements.xml file for the Web Part. The group is set to "Custom" by default. You can create a custom group by changing the Value attribute. For example, to create a Finance group, set the value to "Finance" (<Property Name="Group" Value="Finance" />).

To add the grid utilities code

  1. In Solution Explorer, right-click the JSGrid project, point to Add, and then click New Folder. Name the folder GridUtils.

  2. Right-click the GridUtils folder, point to Add, and then click New Item.

  3. In the Add New Item dialog box, expand the Visual C# node, select Code, and then select Code File. Name the file GridUtilities.cs.

  4. Repeat the previous two steps to create a C# code file, but name the file GridData.cs.

  5. Copy the contents of GridUtilities.cs and GridData.cs, shown in the following examples, into their respective files in the GridUtils folder.

    GridUtilities.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using Microsoft.SharePoint.JSGrid;
    using Microsoft.SharePoint;
    
    namespace JSGridSample.GridUtilityLib
    {
        public static class GridUtilities
        {
            public static IList<GridColumn> GetGridColumns(DataTable table)
            {
                List<GridColumn> r = new List<GridColumn>();
                foreach (DataColumn iterator in table.Columns)
                {
                    /* Columns are visible in the grid; we don't want these
                       as grid columns. */
                    // HierarchyParentKey is used in the how to: Create a Hierarchy Grid topic.
    
                    if (iterator.ColumnName != "Key" 
                            && iterator.ColumnName != GridSerializer.DefaultGridRowStyleIdColumnName
                            //&& iterator.ColumnName != GridSerializer.DefaultGanttBarStyleIdsColumnName 
    
                            // uncomment for the Create a Gantt Chart Using the JS Grid Control how-to.
                            && iterator.ColumnName != "HierarchyParentKey"
    
                            // The costq and Quart fields are used in the Create a Pivot Grid Using the JS Grid Control how-to.
                            && iterator.ColumnName.Substring(0, 5) != "costq"
                            && iterator.ColumnName.Substring(0, 5) != "Quart")
                    {
                        GridColumn col = new GridColumn();
                        // Point the column at a fieldKey name.
                        col.FieldKey = iterator.ColumnName;
                        // Give the column header a name.
                        col.Name = iterator.ColumnName;
                        // Define the column width.
                        col.Width = 210;
    
                        // Define column settings.
                        if (iterator.ColumnName == "Department")
                        {
                            col.IsHidable = false;
                        }
                        if (iterator.ColumnName == "Yearly Estimate")
                        {
                            col.IsSortable = true;
                        }
    
                        // Add the column.
                        r.Add(col);
                    }
                }
                return r;
            }
    
            public static IList<GridField> GetGridFields(DataTable table)
            {
                List<GridField> r = new List<GridField>();
    
                foreach (DataColumn iterator in table.Columns)
                {
                    GridField field = new GridField();
                    field = formatGridField(field, iterator);
    
                    r.Add(field);
                }
                return r;
            }
    
            /** This code matches the propType of the incoming column with the 
                outgoing grid field. HierarchyParentKey is used in the Hierarchy how to. **/
            public static GridField formatGridField(GridField gf, DataColumn dc)
            {
                // Set field key name.
                gf.FieldKey = dc.ColumnName;
                // When in doubt, serialize the data value.
                gf.SerializeDataValue = true;
                if (dc.ColumnName != "Key" 
                   && dc.ColumnName != GridSerializer.DefaultGridRowStyleIdColumnName
                   // Uncomment for the Create a Gantt Chart Using JS Grid how-to.
                   // && dc.ColumnName != GridSerializer.DefaultGanttBarStyleIdsColumnName  
                   && dc.ColumnName != "HierarchyParentKey")
                {
                    // Determine whether the field is timephased.
                    if (dc.ColumnName.Substring(0, 5) == "costq")
                    {
                    }
                    if (dc.ColumnName.Substring(0, 5) == "Quarter")
                    {
                        /* Ensure that the timephased column headers are
                           always read-only despite the grid settings. */
                        gf.EditMode = EditMode.ReadOnly;
                    }
    
                    // Add properties based on the type.
                    if (dc.DataType == typeof(String))
                    {
                        gf.PropertyTypeId = "String";
                        /* The Localizer determines how we render the 
                           underlying data on screen. */
                        gf.Localizer = (ValueLocalizer)delegate(DataRow row, object toConvert)
                        {
                            return toConvert == null ? "" : toConvert.ToString();
                        };
                        /* The Serialization type is a required property. */
                        gf.SerializeLocalizedValue = true;
                        gf.SerializeDataValue = false;
                    }
                    else if (dc.DataType == typeof(Int16)
                        || dc.DataType == typeof(Int32) 
                        || dc.DataType == typeof(Int64)
                        || dc.DataType == typeof(Decimal)
                        || dc.DataType == typeof(Double))
    
                    {
                        gf.PropertyTypeId = "JSNumber";
                        /* The Localizer determines how we render the 
                           underlying data on screen. */
                        gf.Localizer = (ValueLocalizer)delegate(DataRow row, object toConvert)
                        {
                            return toConvert == null ? "" : toConvert.ToString();
                        };
                        // Right align numeric columns
                        gf.DefaultCellStyleId = "TextRightAlign";
    
                        /* The Serialization type is a required property. */
                        gf.SerializeLocalizedValue = true;
                        gf.SerializeDataValue = false;
                    }
                    else if (dc.DataType == typeof(Hyperlink))
                    {
                        gf.PropertyTypeId = "Hyperlink";
                        gf.Localizer = (ValueLocalizer)delegate(DataRow row, object toConvert)
                        {
                            return toConvert == null ? "" : toConvert.ToString();
                        };
                        gf.SerializeLocalizedValue = false;
                        gf.SerializeDataValue = true;
                    }
                    else if (dc.DataType == typeof(bool))
                    {
                        gf.PropertyTypeId = "CheckBoxBoolean";
                        gf.SerializeDataValue = true;
                        gf.SerializeLocalizedValue = false;
                    }
                    else if (dc.DataType == typeof(DateTime))
                    {
                        gf.PropertyTypeId = "JSDateTime";
                        gf.Localizer = (ValueLocalizer)delegate(DataRow row, object toConvert)
                        {
                            return toConvert == null ? "" : toConvert.ToString();
                        };
                        gf.SerializeDataValue = true;
                        gf.SerializeLocalizedValue = true;
                    }
                    else
                        throw new Exception("No PropTypeId defined for this datatype" + dc.DataType);
                }
                return gf;
            }
        }
    }
    

    Setting the GridField.SerializeDataValue property to true instructs the serializer to serialize the actual date value. Setting the GridField.SerializeLocalizedValue property to true instructs the serializer to serialize the displayed or localized date value (for example, the date value displayed in the mm/yyyy format).

    GridData.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Web.UI.WebControls;
    using Microsoft.SharePoint.JSGrid;
    
    namespace JSGridSample.GridUtilityLib
    {
        public class GridData
        {
            /**
             * This method returns a Basic data table with a 'Key' column
             * and sample column of various types.
             * @param numRows is the number of rows of data to create.
             * */
            Random _rand = new Random();
            public virtual DataTable Data(int numRows)
            {
                // Create and initialize the data table.
                DataTable data = new DataTable();
                data = new DataTable();
                data.Locale = System.Globalization.CultureInfo.InvariantCulture;
    
    
                // Add the columns that we care about.
                data.Columns.Add(new DataColumn("Key", typeof(Guid)));
                data.Columns.Add(new DataColumn(GridSerializer.DefaultGridRowStyleIdColumnName, typeof(String)));
                data.Columns.Add(new DataColumn("HierarchyParentKey", typeof(Guid)));
                data.Columns.Add(new DataColumn("Title", typeof(string)));
                data.Columns.Add(new DataColumn("Department Manager", typeof(string)));
                data.Columns.Add(new DataColumn("Department", typeof(string)));
                data.Columns.Add(new DataColumn("Start Date", typeof(DateTime)));
                data.Columns.Add(new DataColumn("Finish Date", typeof(DateTime)));
                data.Columns.Add(new DataColumn("CompleteThrough", typeof(DateTime)));
                data.Columns.Add(new DataColumn("Yearly Estimate", typeof(int)));
                data.Columns.Add(new DataColumn("FY 2009 Estimate", typeof(int)));
                data.Columns.Add(new DataColumn("FY 2010 Estimate", typeof(int)));
                data.Columns.Add(new DataColumn("checkbox", typeof(Boolean)));
                data.Columns.Add(new DataColumn("Hyperlink", typeof(Hyperlink)));
                //data.Columns.Add(new DataColumn(GridSerializer.DefaultGanttBarStyleIdsColumnName, typeof(GanttUtilities.CustomBarStyle[]))); // uncomment for the Create a Gantt Chart Using JS Grid how-to.
    
                Guid? parent = null;
                // Create dummy data for the number of rows we have.
                DataRow dr;
                int j = 0;
                for (int i = 0; i < numRows; i++)
                {
                    var curKey = Guid.NewGuid();
    
                    dr = data.NewRow();
                    dr["Key"] = curKey;
    
                    // Used for the hierarchy grid How-to.
                    if (i % 10 == 0)
                    {
                        parent = curKey;
                        j++;
                    }
                    if (parent.HasValue)
                    {
                        dr["HierarchyParentKey"] = parent.Value;
                    }
                    if (parent == null)
                    {
                        parent = curKey;
                    }
                    dr["Title"] = "Task " + j + "." + i % 10;
                    dr["Department Manager"] = "Manager";
                    dr["Department"] = "Department- " + i.ToString();
                    dr["FY 2009 Estimate"] = _rand.Next(1000000) + 30000;
                    dr["FY 2010 Estimate"] = _rand.Next(1000000) + 30000;
                    dr["Yearly Estimate"] = ((int)dr["FY 2009 Estimate"]
                        + (int)dr["FY 2010 Estimate"]) / 2;
                    dr["Start Date"] = DateTime.Now.AddSeconds(_rand.Next(60 * 60 * 24 * 20));
                    dr["Finish Date"] = DateTime.Now.AddSeconds(_rand.Next(60 * 60 * 24 * 20));
                    dr["CompleteThrough"] = DateTime.Now.AddSeconds(_rand.Next(60 * 60 * 24 * 20));
                    dr["checkbox"] = i % 2 != 0;
                    dr["Hyperlink"] = new Hyperlink() { Display = "Contoso", Address = "https://www.contoso.com" };
    
                    data.Rows.Add(dr);
                }
                return data;
            }
        }
    }
    

To modify JSGridWebPartUserControl.ascx.cs

  1. Open JSGridWebPartUserControl.ascx.cs.

  2. Add the following declarations.

    using System.Data;
    using Microsoft.SharePoint.JSGrid;
    using JSGridSample.GridUtilityLib;
    
  3. Replace the contents of the JSGridWebPartUserControl class with the following.

    public partial class JSGridWebPartUserControl : UserControl
        {
            protected global::Microsoft.SharePoint.WebControls.JSGrid _grid;
            protected void Page_Load(object sender, EventArgs e)
            {
                // Build some simple data for the grid to display.
                DataTable data = new GridData().Data(20);
    
                // Create a grid serializer to connect to data.
                GridSerializer gds = new GridSerializer(SerializeMode.Full,
                    data, "Key", new FieldOrderCollection(new String[] { "Department" }),
                    GridUtilities.GetGridFields(data), GridUtilities.GetGridColumns(data));
    
                // Point the grid serializer at the grid serializer data.
                _grid.GridDataSerializer = gds;
    
                // Tell the grid to listen to the GridManager controller.
                _grid.JSControllerClassName = "GridManager";
            }
        }
    

    Note

    The JS Grid control could also be created in the OnPreRender event handler, rather than the On_Load event handler. This would be necessary, for example, if you wanted to add properties to the Web Part.

The GridSerializer obect serializes JS Grid control configuration information and data to a JavaScript Object Notation (JSON) string. The grid control generates the JSON and puts it on the page.

To test the Web Part

  1. In Visual Studio, press F5 to run the project.

  2. Deployment occurs, and the SharePoint site opens. The Web Part is automatically added to the SharePoint 2010 Web Part Gallery.

  3. Open and edit any Web Parts page. You can add the Web Part to any Web Parts page.

  4. Click Insert, click Web Part, and then add JSGridWebPart from the Custom category. The Web Part is displayed on the page.

    Note

    When you close Windows Internet Explorer or press Shift+F5 in Visual Studio, Visual Studio retracts the Web Part (if Auto-retract after debugging is selected in the SharePoint tab of the JSGrid property page) and resets Internet Information Services (IIS). If you click Deploy Solution on the Build menu, Visual Studio deploys the solution on the development computer so that you can use the Web Part independently from Visual Studio.

For more information about how to work with Web Parts, see How to: Work with Web Parts on a Page.

Next Steps

Continue with one of the following procedures:

See Also

Reference

Microsoft.SharePoint.JSGrid

Microsoft.SharePoint.WebControls.JSGrid

Concepts

JS Grid Control