zjy19811001 发表于 2015-9-25 10:15:12

sharepoint中的ListViewWebPart和ViewToolBar的操作

本文内容参考了园子中【涟漪勇】的博客
http://www.cnblogs.com/rippleyong/archive/2008/10/28/1321412.html
感谢作者的贡献

上面的这个ViewToolBar是可以添加到任何地方的,添加的代码如下,他就是一个控件,继承了System.Web.UI.Control


Code
/// <summary>
      /// 添加ViewToolBar
      /// </summary>
      private void addViewToolbar()
      {
             _toolbar = new ViewToolBar();
            SPContext context = SPContext.GetContext(this.Context, _spview.ID, SPContext.Current.List.ID, SPContext.Current.Web);
            toolbar.RenderContext = context;
            Controls.Add(toolbar);
      }
      
还有就是SharePoint中常见到的显示列表条目的那个ListViewWebPart,就是一进入一个列表,在toolbar下面的那个,上面还有列表项的操作菜单
,代码如下


Code
/// <summary>
      /// 添加ListViewWebPart
      /// </summary>
      private void addListViewWebPart()
      {
             _lvwp = new ListViewWebPart();
            lvwp.ListName = SPContext.Current.List.ID.ToString("B").ToUpper();
            lvwp.ViewGuid = _spview.ID.ToString("B").ToUpper();
            lvwp.ViewType = ViewType.Html;
            Controls.Add(lvwp);
      }

有谁知道这个webpart上的列表项的操作菜单(就是,那个单击标题弹出来的,修改,工作流啊,什么的)是否可以移植呢,比如说也像toolbar一样,我想移植到gridview上面去,不知道可以不,希望有答案的人可以共享一下,谢谢了。



Code
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Xml;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

using CodeArt.SharePoint.CamlQuery;

namespace MainPage
{
   
    public class VirusSmartQueryWebPart :BaseSPWebPart
    {
      private ICamlProvider _CamlProvider;
      private string _LayoutControlPath = "";

      private ViewToolBar _toolbar = null;
      private ListViewWebPart _lvwp = null;
      private SPView _spview = null;

      public VirusSmartQueryWebPart()
      {
            _spview = SPContext.Current.List.DefaultView;
      }
      private void ChangeSchemaXmlQuery(XmlDocument doc, string query)
      {
            if (!string.IsNullOrEmpty(query))
            {
                string innerQuery = this.GetInnerQuery(query);
                if (innerQuery != "")
                {
                  XmlNode node = doc.DocumentElement.SelectSingleNode("Query");
                  XmlNode oldChild = node.SelectSingleNode("Where");
                  if (oldChild != null)
                  {
                        node.RemoveChild(oldChild);
                  }
                  XmlNode newChild = doc.CreateElement("Where");
                  newChild.InnerXml = innerQuery;
                  node.AppendChild(newChild);
                  doc.DocumentElement.SelectSingleNode("ViewEmpty").InnerXml = "<HTML><!]></HTML>";
                }
            }
      }
      protected override void CreateChildControls()
      {
            base.CreateChildControls();
            if (_toolbar == null)
            {
                addViewToolbar();
            }
            if (_lvwp == null)
            {
                addListViewWebPart();
            }
            QueryField title = new QueryField("Title");

            this.SetCurrentListViewSchemaQuery(CamlBuilder.Where(title.Contains("1")));

            try
            {
                if (!string.IsNullOrEmpty(this._LayoutControlPath))
                {
                  Control child = this.Page.LoadControl(this._LayoutControlPath);
                  this._CamlProvider = child as ICamlProvider;
                  this.Controls.Add(child);
                }
                else
                {
                  base.RegisterShowToolPanelControl("请打开工具窗格", "设置“布局控件路径(LayoutControlPath)”", "如“~/_CONTROLTEMPLATES/CodeArt_ExampleQueryLayout.ascx");
                }
            }
            catch (Exception exception)
            {
                base.RegisterError(exception);
            }
            // TODO: add custom rendering code here.
            // Label label = new Label();
            // label.Text = "Hello World";
            // this.Controls.Add(label);
      }
      private string GetInnerQuery(string q)
      {
            XmlDocument document = new XmlDocument();
            document.LoadXml(q);
            return document.DocumentElement.InnerXml;
      }

      protected override void OnInit(EventArgs e)
      {
            base.OnInit(e);
            this.EnableViewState = true;
            this.EnsureChildControls();
      }

      protected override void OnLoad(EventArgs e)
      {
            base.OnLoad(e);
            if (this.Page.IsPostBack)
            {
                //CamlExpression expr = null;
                //try
                //{
                //    expr = this.QueryExpression;
                //}
                //catch (Exception exception)
                //{
                //    base.RegisterError(exception);
                //    return;
                //}
                //if (expr != null)
                //{
                //    string qxml = CamlBuilder.Where(this.List, expr);
                //    this.SetCurrentListViewSchemaQuery(qxml);
                //}
                QueryField targetTo = new QueryField("TargetTo");
                QueryField title = new QueryField("Title");
               
                this.SetCurrentListViewSchemaQuery(CamlBuilder.Where(title.Contains("1")));


            }
      }
      /// <summary>
      /// 添加ViewToolBar
      /// </summary>
      private void addViewToolbar()
      {
             _toolbar = new ViewToolBar();
            SPContext context = SPContext.GetContext(this.Context, _spview.ID, SPContext.Current.List.ID, SPContext.Current.Web);
            toolbar.RenderContext = context;
            Controls.Add(toolbar);
      }
      /// <summary>
      /// 添加ListViewWebPart
      /// </summary>
      private void addListViewWebPart()
      {
             _lvwp = new ListViewWebPart();
            lvwp.ListName = SPContext.Current.List.ID.ToString("B").ToUpper();
            lvwp.ViewGuid = _spview.ID.ToString("B").ToUpper();
            lvwp.ViewType = ViewType.Html;
            Controls.Add(lvwp);
      }
      private void SetCurrentListViewSchemaQuery(string qxml)
      {
            if (!string.IsNullOrEmpty(qxml))
            {
                string strB = "{" + this.List.ID.ToString() + "}";
                foreach (System.Web.UI.WebControls.WebParts.WebPart part in base.Zone.WebParts)
                {
                  if (part is ListViewWebPart)
                  {
                        ListViewWebPart part2 = (ListViewWebPart)part;
                        if (string.Compare(part2.ListName, strB, true) != 0)
                        {
                            continue;
                        }
                        if (string.IsNullOrEmpty(qxml))
                        {
                            part2.ListViewXml = this.List.Views.HtmlSchemaXml;
                        }
                        else
                        {
                            XmlDocument doc = new XmlDocument();
                            doc.LoadXml(part2.ListViewXml);
                            this.ChangeSchemaXmlQuery(doc, qxml);
                            part2.ListViewXml = doc.InnerXml;
                        }
                        return;
                  }
                }
            }
      }

      
      public string LayoutControlPath
      {
            get
            {
                return this._LayoutControlPath;
            }
            set
            {
                this._LayoutControlPath = value;
            }
      }

      private SPList List
      {
            get
            {
                return SPContext.Current.List;
            }
      }

      public CamlExpression QueryExpression
      {
            get
            {
                this.EnsureChildControls();
                if (this._CamlProvider != null)
                {
                  return this._CamlProvider.QueryExpression;
                }
                return null;
            }
      }
    }
}


下面是上面用到的BaseSPWebPart和ICamlProvider的源代码,是我反编译了园子中jianyi0115的SmartQuery之后的代码,谢谢了
关于CamlQuery和SmartQuery的详细信息可以访问,这两个是作者写的caml辅助工具和列表查询(目前是单列表,希望作者可以升级为兼容多个列表的查询)辅助工具.
http://www.cnblogs.com/jianyi0115/archive/2008/02/15/1070158.html



Code
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;

namespace MainPage
{
   
    public abstract class BaseSPWebPart : WebPart
    {
      private bool _EnableShowErrorMessage = true;
      private IList<Exception> _Exceptions = new List<Exception>();

      protected BaseSPWebPart()
      {
      }

      protected void AddHtml(string html)
      {
            LiteralControl child = new LiteralControl
            {
                EnableViewState = false,
                Text = html
            };
            this.Controls.Add(child);
      }

      protected void AddHtml(string html, Control ctl)
      {
            LiteralControl child = new LiteralControl
            {
                EnableViewState = false,
                Text = html
            };
            ctl.Controls.Add(child);
      }

      protected string GeyShowToolPanelScript()
      {
            return ("MSOTlPn_ShowToolPane2Wrapper('Edit','129','" + this.ID + "')");
      }

      protected override void OnUnload(EventArgs e)
      {
            base.OnUnload(e);
      }

      protected void RegisterError(Exception ex)
      {
            this._Exceptions.Add(ex);
      }

      protected void RegisterShowToolPanelControl(string msg1, string msg2, string msg3)
      {
            LiteralControl child = new LiteralControl
            {
                Text = "<P><DIV class=\"UserGeneric\">" + msg1 + "<A HREF=\"javascript:" + this.GeyShowToolPanelScript() + "\">" + msg2 + "</A>" + msg3 + "</DIV></P>"
            };
            this.Controls.Add(child);
      }

      protected override void RenderContents(HtmlTextWriter writer)
      {
            base.RenderContents(writer);
            this.RenderErrors(writer);
      }

      protected void RenderError(Exception ex, HtmlTextWriter w)
      {
            if (this._EnableShowErrorMessage)
            {
                w.Write(ex.Message);
                w.Write("<br/>");
                w.Write(ex.StackTrace);
                w.Write("<br/>");
                if (ex.InnerException != null)
                {
                  this.RenderError(ex.InnerException, w);
                }
            }
            else
            {
                w.Write("鍙戠敓閿欒");
            }
      }

      protected void RenderErrors(HtmlTextWriter w)
      {
            if (this._EnableShowErrorMessage && (this._Exceptions.Count != 0))
            {
                foreach (Exception exception in this._Exceptions)
                {
                  w.Write(exception.Message);
                  w.Write("<br/>");
                  w.Write(exception.StackTrace);
                  w.Write("<br/>");
                }
                this._Exceptions.Clear();
            }
      }

      
      public bool EnableShowErrorMessage
      {
            get
            {
                return this._EnableShowErrorMessage;
            }
            set
            {
                this._EnableShowErrorMessage = value;
            }
      }
    }
}


using CodeArt.SharePoint.CamlQuery;

public interface ICamlProvider
{
    CamlExpression QueryExpression { get; }
}

下面的代码是一个查询的webpart,列表开启了访问群体控制,使得用户进入显示列表项页面的时候看到自己可以看到的列表项,要把过滤条件写在
createchildcontrols方法中才可以实现,这个我实验了一个星期啊,

下面的图示为管理员进入列表之后看到的列表项



下面的图示为普通用户进入列表之后的查询界面和看到的列表项,用户所属的sharepoint用户组为“开发部”





Code
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Xml;
using System.Collections.Generic;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

using CodeArt.SharePoint.CamlQuery;

namespace MainPage
{
   
    public class VirusSmartQueryWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
      private QueryField _bulletinTitle;
      private QueryField _bulletinContent;
      private QueryField _bulletinReleaseBeginDT;
      private QueryField _bulletinReleaseEndDT;
      private QueryField _bulletinExpireBeginDT;
      private QueryField _bulletinExpireEndDT;
      private QueryField _bulletinTargetTo;

      private Table table = null;
      private TextBox bulletinTitle = null;
      private TextBox bulletinContent = null;
      private DateTimeControl bulletinReleaseDTBegin = null;
      private DateTimeControl bulletinExpireDTBegin = null;
      private Button btnQuery = null;
      private DateTimeControl bulletinReleaseDTEnd = null;
      private DateTimeControl bulletinExpireDTEnd = null;

      private ICamlProvider _CamlProvider;
      private string _LayoutControlPath = "";
      /// <summary>
      /// 过滤条件表达式
      /// </summary>
      private CamlExpression _camlExpression;

      private ViewToolBar _toolbar = null;
      private ListViewWebPart _lvwp = null;
      private SPView _spview = null;

      /// <summary>
      /// 当前用户所在的SharePoint用户组
      /// </summary>
      private List<string> currUserGroups = null;
      /// <summary>
      /// 当前用户是否公告管理员
      /// </summary>
      private bool IsBulletinAdmin = false;

      public VirusSmartQueryWebPart()
      {
            _spview = SPContext.Current.List.DefaultView;
            addCurrentUserGroup();
            isBulletinAdmin();
         
      }
      /// <summary>
      /// 将当前用户所在的用户组添加到currUserGroup集合
      /// </summary>
      private void addCurrentUserGroup()
      {
            currUserGroups = new List<string>();
            currUserGroups.Clear();
            SPGroupCollection groups = SPContext.Current.Web.CurrentUser.Groups;
            foreach (SPGroup g in groups)
            {
                currUserGroups.Add(g.Name);
            }

      }
      /// <summary>
      /// 判断当前用户是否公告管理员
      /// </summary>
      /// <returns></returns>
      private void isBulletinAdmin()
      {
            if (currUserGroups.Count > 0)
            {
                foreach (string s in currUserGroups)
                {
                  if (s.Equals("公告管理员"))
                  {
                        IsBulletinAdmin = true;
                        break;
                  }
                }
            }

      }
      private void ChangeSchemaXmlQuery(XmlDocument doc, string query)
      {
            if (!string.IsNullOrEmpty(query))
            {
                string innerQuery = this.GetInnerQuery(query);
                if (innerQuery != "")
                {
                  XmlNode node = doc.DocumentElement.SelectSingleNode("Query");
                  XmlNode oldChild = node.SelectSingleNode("Where");
                  if (oldChild != null)
                  {
                        node.RemoveChild(oldChild);
                  }
                  XmlNode newChild = doc.CreateElement("Where");
                  newChild.InnerXml = innerQuery;
                  node.AppendChild(newChild);
                  doc.DocumentElement.SelectSingleNode("ViewEmpty").InnerXml = "<HTML><!]></HTML>";
                }
            }
      }
      protected override void CreateChildControls()
      {
            base.CreateChildControls();
            _bulletinTargetTo = new QueryField(SPContext.Current.List.Fields["目标访问群体"].InternalName);
            if (!IsBulletinAdmin)
            {
                _camlExpression = _bulletinTargetTo.Contains(SPContext.Current.Web.CurrentUser.Groups.Name);
            }
            if (_camlExpression != null)
            {
                this.SetCurrentListViewSchemaQuery(CamlBuilder.Where(_camlExpression));
            }

            if (table != null)
            {
                this.Controls.Add(table);
            }
            else
            {
                createTable();
                this.Controls.Add(table);
            }
      }
      private string GetInnerQuery(string q)
      {
            XmlDocument document = new XmlDocument();
            document.LoadXml(q);
            return document.DocumentElement.InnerXml;
      }

      protected override void OnInit(EventArgs e)
      {
            base.OnInit(e);
            this.EnableViewState = true;
            this.EnsureChildControls();
      }
      /// <summary>
      /// 创建查询界面布局
      /// </summary>
      private void createTable()
      {
            table = new Table();
            TableRow tr1 = new TableRow();

            TableCell cell11 = new TableCell();
            cell11.Text = "公告标题";
            tr1.Cells.Add(cell11);

            TableCell cell12 = new TableCell();
            bulletinTitle = new TextBox();
            bulletinTitle.ID = "bulletinTitle";
            bulletinTitle.Text = "";
            cell12.Controls.Add(bulletinTitle);
            tr1.Cells.Add(cell12);

            TableCell cell13 = new TableCell();
            cell13.Text = "公告发布时间";
            tr1.Cells.Add(cell13);

            TableCell cell14 = new TableCell();
            bulletinReleaseDTBegin = new DateTimeControl();
            bulletinReleaseDTBegin.ID = "bulletinReleaseDT";
            bulletinReleaseDTBegin.DateOnly = true;
            cell14.Controls.Add(bulletinReleaseDTBegin);
            tr1.Cells.Add(cell14);

            TableCell cell15 = new TableCell();
            cell15.Text = "公告过期时间";
            tr1.Cells.Add(cell15);

            TableCell cell16 = new TableCell();
            bulletinExpireDTBegin = new DateTimeControl();
            bulletinExpireDTBegin.DateOnly = true;
            bulletinExpireDTBegin.ID = "bulletinExpireDTBegin";
            cell16.Controls.Add(bulletinExpireDTBegin);
            tr1.Cells.Add(cell16);

            TableCell cell17 = new TableCell();
            btnQuery = new Button();

            btnQuery.ID = "btnQuery";
            btnQuery.Text = "查询";
            btnQuery.Click += new EventHandler(btnQuery_Click);
            cell17.Controls.Add(btnQuery);
            tr1.Cells.Add(cell17);

            table.Rows.Add(tr1);

            TableRow tr2 = new TableRow();

            TableCell cell21 = new TableCell();
            cell21.Text = "公告内容";
            tr2.Cells.Add(cell21);

            TableCell cell22 = new TableCell();
            bulletinContent = new TextBox();
            bulletinContent.ID = "bulletinContent";
            bulletinContent.Text = "";
            cell22.Controls.Add(bulletinContent);
            tr2.Cells.Add(cell22);

            TableCell cell23 = new TableCell();
            cell23.Text = "到";
            tr2.Cells.Add(cell23);

            TableCell cell24 = new TableCell();
            bulletinReleaseDTEnd = new DateTimeControl();
            bulletinReleaseDTEnd.ID = "bulletinReleaseDTEnd";
            bulletinReleaseDTEnd.DateOnly = true;
            cell24.Controls.Add(bulletinReleaseDTEnd);
            tr2.Cells.Add(cell24);

            TableCell cell25 = new TableCell();
            cell25.Text = "到";
            tr2.Cells.Add(cell25);

            TableCell cell26 = new TableCell();
            bulletinExpireDTEnd = new DateTimeControl();
            bulletinExpireDTEnd.DateOnly = true;
            bulletinExpireDTEnd.ID = "bulletinExpireDTEnd";
            cell26.Controls.Add(bulletinExpireDTEnd);
            tr2.Cells.Add(cell26);

            TableCell cell27 = new TableCell();
            cell27.Text = "";
            tr2.Cells.Add(cell27);

            table.Rows.Add(tr2);

      }
      /// <summary>
      /// 单击查询按钮
      /// </summary>
      /// <param name="sender"></param>
      /// <param name="e"></param>
      void btnQuery_Click(object sender, EventArgs e)
      {
            _bulletinTitle = new QueryField("Title");
            _bulletinContent = new QueryField(List.Fields["公告内容"].InternalName);
            _bulletinReleaseBeginDT = new QueryField(List.Fields["公告发布时间"].InternalName);
            _bulletinReleaseEndDT = new QueryField(List.Fields["公告发布时间"].InternalName);
            _bulletinExpireBeginDT = new QueryField(List.Fields["公告过期时间"].InternalName);
            _bulletinExpireEndDT = new QueryField(List.Fields["公告过期时间"].InternalName);

            //throw new NotImplementedException();
            if (!string.IsNullOrEmpty(bulletinTitle.Text))
            {
                if (_camlExpression == null)
                {
                  _camlExpression = _bulletinTitle.Contains(bulletinTitle.Text.Trim());
                }
                else
                {
                  _camlExpression = _camlExpression && _bulletinTitle.Contains(bulletinTitle.Text.Trim());
                }
            }
            if (!string.IsNullOrEmpty(bulletinContent.Text))
            {
                if (_camlExpression == null)
                {
                  _camlExpression = _bulletinContent.Contains(bulletinContent.Text.Trim());
                }
                else
                {
                  _camlExpression = _camlExpression && _bulletinContent.Contains(bulletinContent.Text.Trim());
                }
            }
            if (!bulletinReleaseDTBegin.IsDateEmpty && !bulletinReleaseDTEnd.IsDateEmpty)
            {
                if (_camlExpression == null)
                {
                  _camlExpression = _bulletinReleaseBeginDT.MoreEqual(bulletinReleaseDTBegin.SelectedDate) && _bulletinReleaseEndDT.LessEqual(bulletinReleaseDTEnd.SelectedDate);


                }
                else
                {
                  _camlExpression = _camlExpression && _bulletinReleaseBeginDT.MoreEqual(bulletinReleaseDTBegin.SelectedDate) && _bulletinReleaseEndDT.LessEqual(bulletinReleaseDTEnd.SelectedDate);

                }
            }
            if (!bulletinExpireDTBegin.IsDateEmpty && !bulletinExpireDTEnd.IsDateEmpty)
            {
                if (_camlExpression == null)
                {
                  _camlExpression = _bulletinExpireBeginDT.MoreEqual(bulletinExpireDTBegin.SelectedDate) && _bulletinExpireEndDT.LessEqual(bulletinExpireDTEnd.SelectedDate);

                }
                else
                {
                  _camlExpression = _camlExpression && _bulletinExpireBeginDT.MoreEqual(bulletinExpireDTBegin.SelectedDate) && _bulletinExpireEndDT.LessEqual(bulletinExpireDTEnd.SelectedDate);


                }
            }
            if (QueryExpression != null)
            {
                this.SetCurrentListViewSchemaQuery(CamlBuilder.Where(QueryExpression));
            }
      }
      protected override void OnLoad(EventArgs e)
      {
            base.OnLoad(e);

      }
      /// <summary>
      /// 添加ViewToolBar
      /// </summary>
      private void addViewToolbar()
      {
            _toolbar = new ViewToolBar();
            SPContext context = SPContext.GetContext(this.Context, _spview.ID, SPContext.Current.List.ID, SPContext.Current.Web);
            _toolbar.RenderContext = context;
            Controls.Add(_toolbar);
      }
      /// <summary>
      /// 添加ListViewWebPart
      /// </summary>
      private void addListViewWebPart()
      {
            _lvwp = new ListViewWebPart();
            _lvwp.ListName = SPContext.Current.List.ID.ToString("B").ToUpper();
            _lvwp.ViewGuid = _spview.ID.ToString("B").ToUpper();
            _lvwp.ViewType = ViewType.Html;
            Controls.Add(_lvwp);
      }
      private void SetCurrentListViewSchemaQuery(string qxml)
      {
            if (!string.IsNullOrEmpty(qxml))
            {
                string strB = "{" + this.List.ID.ToString() + "}";
                foreach (System.Web.UI.WebControls.WebParts.WebPart part in base.Zone.WebParts)
                {
                  if (part is ListViewWebPart)
                  {
                        ListViewWebPart part2 = (ListViewWebPart)part;
                        if (string.Compare(part2.ListName, strB, true) != 0)
                        {
                            continue;
                        }
                        if (string.IsNullOrEmpty(qxml))
                        {
                            part2.ListViewXml = this.List.Views.HtmlSchemaXml;
                        }
                        else
                        {
                            XmlDocument doc = new XmlDocument();
                            doc.LoadXml(part2.ListViewXml);
                            this.ChangeSchemaXmlQuery(doc, qxml);
                            part2.ListViewXml = doc.InnerXml;
                        }
                        return;
                  }
                }
            }
      }

      
      public string LayoutControlPath
      {
            get
            {
                return this._LayoutControlPath;
            }
            set
            {
                this._LayoutControlPath = value;
            }
      }

      private SPList List
      {
            get
            {
                return SPContext.Current.List;
            }
      }

      public CamlExpression QueryExpression
      {
            get
            {
                this.EnsureChildControls();
                if (this._camlExpression != null)
                {
                  return this._camlExpression;
                }
                return null;
            }
      }
    }
}
页: [1]
查看完整版本: sharepoint中的ListViewWebPart和ViewToolBar的操作