DataGrid to a SharePoint Web Part (with Sortable Columns)

1. Add the DataGrid to the Controls collection

protected override void CreateChildControls()

{

…

dgEmployees = new DataGrid();

dgEmployees.EnableViewState=true;

dgEmployees.AutoGenerateColumns=false;

dgEmployees.AllowSorting=true;

 

dgEmployees.HeaderStyle.BackColor=System.Drawing.Color.SlateGray;

dgEmployees.HeaderStyle.Font.Bold=true;

dgEmployees.HeaderStyle.HorizontalAlign=HorizontalAlign.Center;

 

dgEmployees.AlternatingItemStyle.BackColor=System.Drawing.Color.Gainsboro;

 

BoundColumn col = new BoundColumn();

col.HeaderText = “Last Name”;

col.DataField = “urn:schemas-microsoftcom:sharepoint:portal:profile:LastName”;

col.SortExpression = “urn:schemas-microsoft-com:sharepoint:portal:profile:LastName”;

dgEmployees.Columns.Add(col);

//add additional columns here based on code above

 

dgEmployees.Width=System.Web.UI.WebControls.Unit.Percentage(100);

DataSet ds = this.Query(this.TextBoxQuery.Text);

DataView dv = ds.Tables[0].DefaultView;

dgEmployees.DataSource=dv;

dgEmployees.DataBind();

dgEmployees.SortCommand += new DataGridSortCommandEventHandler(dgEmployees_SortCommand);

Controls.Add(dgEmployees);

}

2. Render the control

protected override void RenderWebPart(HtmlTextWriter output)

{

this.EnsureChildControls();

…

this.dgEmployees.RenderControl(output);

…

}

3. Add the sort method

private void dgEmployees_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)

{

string sortExpression = (string)ViewState[“SortExp”];

string sortDirection = (string)ViewState[“SortDir”];

 

if(sortExpression != e.SortExpression)

{

sortExpression = e.SortExpression;

sortDirection = “asc”;

}

else

{

if(sortDirection == “asc”)

sortDirection = “desc”;

else

sortDirection = “asc”;

}

 

ViewState[“SortExp”] = sortExpression;

ViewState[“SortDir”] = sortDirection;

}

4. Bind the DataGrid on PreRender

protected override void OnPreRender(EventArgs e)

{

DataSet ds = this.Query(this.TextBoxQuery.Text);

DataView dv = ds.Tables[0].DefaultView;

if (ViewState[“SortExp”] != null &&  ViewState[“SortDir”] != null)

{

dv.Sort = ViewState[“SortExp”] + ” ” + ViewState[“SortDir”];

}

this.dgEmployees.DataSource = dv;

this.dgEmployees.DataBind();

base.OnPreRender (e);

}