Saturday, July 01, 2006

WSS v3 Development Pattern - Binding a SPGridView to a SPDataSource in C#


The WSS v3 development pattern below illustrates a simple example for binding a SPGridView object to a SPDataSource object.  The pattern assumes a member variable m_grid of type SPGridView has been declared in your web part.

[c#]

protected override void CreateChildControls()
{
  SPWeb web = SPContext.Current.Web;
  using (SPDataSource ds = new SPDataSource())
  {
    ds.List = 
      web.Lists[new Guid("FB0ADC39-3792-4FC7-949C-F033D0671691")];
    ds.DataSourceMode = SPDataSourceMode.List;
    ds.IncludeHidden = false;
    ds.Scope = SPViewScope.Recursive;

    m_grid = new SPGridView();
    m_grid.DataSource = ds;
    m_grid.AutoGenerateColumns = false;

    m_grid.Columns.Clear();

    BoundField t = new BoundField();
    t.DataField = "Title";
    t.HeaderText = "Title";
    m_grid.Columns.Add(t);

    BoundField b = new BoundField();
    b.DataField = "Body";
    b.HeaderText = "Body";    
    b.HtmlEncode = false;
    m_grid.Columns.Add(b);

    m_grid.DataBind();
  }
  Controls.Add(m_grid);
}

Here’s the ouput:

Bindingspdataview

Post a Comment