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.


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;


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

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


Here’s the ouput:


Post a Comment