I'm trying to build a SPGrid based on a particular List and View in a webpart (Visual WebPart). This should be basic, but when I add the webpart to the page I keep getting the error message "Value does not fall within expected range", and no webpart showing on screen.
All of this needs to be done programmatically. My code looks like the following:
protected void Page_Load(object sender, EventArgs e)
{
spList = SPContext.Current.Web.Lists.TryGetList("MyDocLibrary");
spView = spList.Views["Demo"];
String viewFields = string.Empty;
string orderBy = string.Empty;
viewFields = BuildColumns(spView, spGrid);
dataSource.DataSourceMode = SPDataSourceMode.List;
dataSource.SelectCommand = viewFields + "<Query>" + spView.Query + orderBy + "</Query>";
dataSource.List = spList;
Parameter listIdParam = new Parameter("ListID");
listIdParam.DefaultValue = spList.ID.ToString("B").ToUpper();
dataSource.SelectParameters.Add(listIdParam);
spGrid.DataSource = dataSource;
spGrid.DataBind();
}
private string BuildColumns(SPView myView, SPGridView grid)
{
string viewFields = "<view><ViewFields>";
SPViewFieldCollection spViewFields = myView.ViewFields;
BoundField col = new BoundField();
for (int i = 0; i < spViewFields.Count; i++)
{
var field = myView.ParentList.Fields.GetFieldByInternalName(spViewFields[i]);
if(!field.Hidden)
{
col = new BoundField();
col.HeaderText = field.Title;
col.DataField = field.InternalName;
col.SortExpression = field.InternalName;
grid.Columns.Add(col);
viewFields += "<FieldRef Name=\"" + field.InternalName + "\"/>";
}
}
viewFields += "</ViewFields></view>";
return viewFields;
}
I just don't know what I'm doing wrong. Other blogs haven't helped me so far.
