VisualStudio

VisualStudio

Microsoft Visual Studio Portal

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

Sponsors
Comments
How can I enable inline editing in the SPGridView and then save the modified rows?
Add a Comment:
Already a member? Log In
Sponsors
About the Author

18 Kudos
Top Geek Articles
Why every guy should buy their girlfriend Wii Fit.
Gratuitous...
Astronomy Picture Of The Day
This picture makes us feel very very small.
Hottest Girl Superhero List
A list of female video-game characters you should check out.
More From Zimbio
Copyright © 2009 - Zimbio, Inc. Some rights reserved.