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();
            spGrid.DataSource = dataSource;

 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]);

                        col = new BoundField();
                        col.HeaderText = field.Title;
                        col.DataField = field.InternalName;
                        col.SortExpression = field.InternalName;
                        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.

  • Forgot to add, when debugging it gets all the way to spGrid.Databind() Ok. – Cann0nF0dder Jun 11 '12 at 10:00

Ok. I was being silly. I'm using a visual webpart, but the blogs I've been reading from were for 2007 webparts.

In my OnInit, I was setting

spGrid = new SPGridView();
dataSource = new SPDataSource();

which of course reset all the settings of the SPGridView and SPDataSource I set in the ascx page. Therefore AutoGenerateColumns were set back to true, causing the error.

I also used SPBoundField instead of BoundField, although that didn't make any difference with the error I was getting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.