Friday, August 19, 2011

Creating Custom SPGridView – Part 1

In this blog we will see the simplest way to create a SPGridView, the basic steps would be :

1.     Set property AutoGenerateColumns to false

2.     Create Columns as SPBoundField and associate te Data field to the Data source field

3.     Bind the SPGridView to the datasource and that is it

 

Let us now get to the code and see the how easily a simple SPGridView is done. I have created this inside a web part. In future blogs I would like to explore rich functionalities of the SPGridView and their usage. This SPGridView control is used in the all the list views. Thus, if required we can create similar grid views using this rich control.

I am providing the whole code in one go with some comments in between the code lines.

public class MySPGridViewProjects: System.Web.UI.WebControls.WebParts.WebPart

{

/// <summary>

/// Creates a SPGridView similar to list with custom functionalities

/// </summary>

#region Variables + Controls

Table table;

SPGridView spgvAllProjects;

#endregion

#region Create Child Controls

protected override void CreateChildControls()

{

base.CreateChildControls();

try

{

//Create Controls

      table = new Table();

      this.Controls.Add(table);

      ////All Projects GridView

      spgvAllProjects = new SPGridView();

      spgvAllProjects.ID = "spgvAllProjects";

      spgvAllProjects.AutoGenerateColumns = false;

      spgvAllProjects.RowStyle.BackColor = Color.LightGray;

      spgvAllProjects.AlternatingRowStyle.BackColor = Color.White;

      //----Add to Table ---

      TableRow trAllProjGrid = new TableRow();

      TableCell tcAllProjGrid = new TableCell();

      tcAllProjGrid.Controls.Add(spgvAllProjects);

      trAllProjGrid.Cells.Add(tcAllProjGrid);

      table.Rows.Add(trAllProjGrid);

      ////Active Projects

      PopulateAllProjects("Title", "asc");

      ////Set Web Part Properties

      this.ChromeType = PartChromeType.TitleOnly;

      this.Title = "All Projects";

}

catch (Exception ex)

{

String Message = ex.Message;

}

}

#endregion

Now before I move further, I would like to say that I did not take the pain to create a data table to bind to the SPGridView. For keeping it short I have used the data from a simple list. If you want you can create a data source of your choice. In this case I have taken all the items available from MyList. While creating the bound fields please keep in mind that the data fields should match to the Field names of the List.

#region Populate All Projects

private void PopulateAllProjects(string SortExpression, string NewSortDirection)

{

////Get the Selected Project IDs

      #region Grid View Fields

      SPBoundField boundField = new SPBoundField();

      boundField.HeaderText = "Project ID";

      boundField.DataField = "Title";

      boundField.ControlStyle.CssClass = "ms-vb2";

      spgvAllProjects.Columns.Add(boundField);

 

      boundField = new SPBoundField();

      boundField.HeaderText = "Project Name";

      boundField.DataField = "Name";

      boundField.ControlStyle.CssClass = "ms-vb2";

      spgvAllProjects.Columns.Add(boundField);

 

     

boundField = new SPBoundField();

      boundField.HeaderText = "Project Manager";

////Filed name has got a space inbetween

      boundField.DataField = "Project_x0020_Manager";

      boundField.ControlStyle.CssClass = "ms-vb2";

      spgvAllProjects.Columns.Add(boundField);

     

////The Hidden column to populate Status with image, we will see this

//// Part 2 of creating custom spgridview

      boundField = new SPBoundField();

      boundField.HeaderText = "Status";

      boundField.DataField = "Status";

      boundField.ControlStyle.CssClass = "ms-vb2";

      boundField.Visible = false;

      spgvAllProjects.Columns.Add(boundField);

 

//// Get the data source

      DataTable dt = GetAllProjectsToDisplay();

      try

      {

        if (dt != null && dt.Rows.Count > 0)

        {

            DataView dv = new DataView(dt);

            ////Sort the DataView

            if (!string.IsNullOrEmpty(SortExpression) && !string.IsNullOrEmpty(NewSortDirection))

            {

                  dv.Sort = SortExpression + " " + NewSortDirection;

            }

            ////DG data source

            spgvAllProjects.DataSource = dv;

            ////Data binding

            spgvAllProjects.DataBind();

         }

       }

       catch (Exception ex)

       {

       PortalLog.LogString("Exception in - Create Child Control :" + ex.Message);

        }

 }

////Get your data to display

#region Get Data Source

private DataTable GetAllProjectsToDisplay()

{

DataTable dt = null;

      SPWeb oWeb = SPContext.Current.Web;

      SPList oList = oWeb.Lists[“MyList”];

      try

      {

       ////Run a query to fetch All Project Data

       SPQuery oSPquer = new SPQuery();

       oSPquer.Query = "<Where><And><Eq></Eq></And></Where>";

       SPListItemCollection oItemColl = oList.GetItems(oSPquer);

       if (oItemColl.Count > 0)

           {

                dt = oItemColl.GetDataTable();

           }

       }

       catch (Exception ex)

       {

       }

       return dt;

 }

#endregion

 

Hopefully you have the GridView ready. This was very simple, though you could find some extra bit of coding. These have been kept for the Part 2, where we will add sorting, filtering, paging, menu field etc., to enrich our GridView.


If you have a more elegant solution – please post a comment… I’ll be happy to hear. Thanks for reading.

...HaPpY CoDiNg

Partha (Aurum)

 

 

2 comments:

  1. Thank you for the info. It sounds pretty user friendly. I guess I’ll pick one up for fun. thank u


    ASC Coding

    ReplyDelete
  2. nice post, can you post SPGridview Paging in this example ? thanks

    ReplyDelete