如何将控件添加到 Web 部件(SharePoint、C#)?

Posted

技术标签:

【中文标题】如何将控件添加到 Web 部件(SharePoint、C#)?【英文标题】:How do I add controls to a webpart (SharePoint, C#)? 【发布时间】:2013-09-24 17:41:13 【问题描述】:

基本上情况如下:

下图是网站上实际网页的模型 看起来像。 编程是声明性的,并利用 C#、SQL Server 2008。可视化 Studios 2010(SharePoint 解决方案项目)、SharePoint 2010、Webparts、javascript 和 jQuery。 目前,仅单击编辑按钮(编辑分配、添加新 分配)允许你编辑这些项目——一个用户去另一个 启用控件的表单(这是一个 aspx 表单),进行更改, 并保存。 但是,每个项目都需要在此页面上进行编辑。所以每一项 将需要一个启用控件的编辑按钮、一个保存按钮和 取消按钮。 Allocation Available 需要是一个是/否单选按钮并且需要是 可从此页面进行编辑。 SPR/JDHF 分配需要是一个文本框,并且需要可从 这个页面。 SPR 源需要是下拉列表并从查找管理中拉取 数据库 & 需要可从此页面进行编辑。 分配注释必须是多行文本框,并且必须是 可从此页面进行编辑。 所有项目都需要在页面上进行编辑,因此每个项目都需要 有一个编辑、保存和取消按钮,每个项目的每一行都有一个 这些选项卡中的每一个(管理 ACE、摘要视图等实际上都是 网页部分)

我没有第一个线索如何去做这件事。如果有人能指出我正确的方向,或许可以引导我完成如何添加这些控件中的一个,然后我可以从学习中完成其余的工作,我将不胜感激。谢谢。

网站模型:

页面代码:

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
//Data Controls
using System.Runtime.InteropServices;
using System.Data;
using System.Collections.Specialized;
using System.Data.SqlClient;
using IDE_Utility.DBConnection;
using IDE_Utility.ErrorLogging;
using System.Text;


namespace GIK30.ACEAllocation30

    [ToolboxItemAttribute(false)]
    public class ACEAllocation30 : WebPart
    
        private bool _error = false;
        private string _myProperty = null;
        private Label m_lblMsg;
        private Button m_NewAllocation_Button;
        private HttpResponse Response = HttpContext.Current.Response;

        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("My Property Group")]
        [WebDisplayName("MyProperty")]
        [WebDescription("Meaningless Property")]
        public string MyProperty
        
            get
            
                if (_myProperty == null)
                
                    _myProperty = "";
                
                return _myProperty;
            
            set
                                                                                                                          
                _myProperty = value;
            
        

        public ACEAllocation30()
        
            this.ExportMode = WebPartExportMode.All;
        

        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()
        
            if (!_error)
            
                SPSite site = SPContext.Current.Site;
                DataSet DsAllocation = new DataSet();
                DataView DvAllocation = null;
                DataSet DsACE = new DataSet();
                DataRow DrACE;
                int ACEID = 0;

                if (site != null)
                
                    using (SPWeb web = site.OpenWeb())
                    
                        try
                        
                            int.TryParse(Page.Request["ACEID"], out ACEID);
                            int UserID = GIK20_CodeLibrary.GetUserID(SPContext.Current.Web);
                            StringCollection Access = GIK20_CodeLibrary.GetUserAccessForACE(UserID, ACEID);
                            bool IsACEAdmin = GIK20_CodeLibrary.IsUserACEAdmin(Access);
                            bool IsContracts = GIK20_CodeLibrary.IsUserAllocationSpecialist(Access);

                            // Make sure the ACE exists first
                            Boolean IsACE = false;
                            SqlParameter sqlParamACEID = new SqlParameter();
                            sqlParamACEID.ParameterName = "@aceid";
                            sqlParamACEID.DbType = DbType.Int32;
                            sqlParamACEID.Value = ACEID;

                            SqlParameter[] sqlParams = new SqlParameter[]
                            
                                sqlParamACEID
                            ;
                            try
                            
                                DsACE = DBConnection.GetDataSet("getAceInfo", CommandType.StoredProcedure, sqlParams);
                            
                            catch (Exception ex)
                            
                                HandleException(ex);
                                IDEErrLogging.LogError(new IDEException("ACE Allocation: Validate ACE: Error on Stored Procedure: getAceInfo", ex), true, false, SPContext.Current.Web);
                            
                            if (DsACE != null)
                            
                                if (DsACE.Tables[0].Rows.Count == 1)
                                    IsACE = true;
                            

                            if (IsACE)
                            
                                base.CreateChildControls();
                                DrACE = DsACE.Tables[0].Rows[0];

                                //strSQL = "select * from ACE_Allocation where ACEID = " + ACEID.ToString();
                                try
                                
                                    sqlParamACEID = new SqlParameter();
                                    sqlParamACEID.ParameterName = "@aceid";
                                    sqlParamACEID.DbType = DbType.Int32;
                                    sqlParamACEID.Value = ACEID;

                                    sqlParams = new SqlParameter[]
                                    
                                        sqlParamACEID
                                    ;
                                    DsAllocation = DBConnection.GetDataSet("getACeAllocation", CommandType.StoredProcedure, sqlParams);
                                    DvAllocation = DsAllocation.Tables[0].DefaultView;
                                    DvAllocation.Sort = "FY, AllocationType";
                                
                                catch (Exception ex)
                                
                                    HandleException(ex);
                                    IDEErrLogging.LogError(new IDEException("ACE Allocation: Error on ACE Allocation Stored Procedure: getACeAllocation", ex), true, false, SPContext.Current.Web);
                                

                                // Check to see if edit controls are enabled
                                Boolean enableStatus = false;
                                if (IsACEAdmin || IsContracts)
                                    enableStatus = true;

                                //enableStatus = GIK20_CodeLibrary.CheckUserInGroup(myWeb, statusArray);

                                string AllocationAvail = "No";
                                if (DrACE["AllocationAVailable"].Equals(true))
                                
                                    AllocationAvail = "Yes";
                                


                                StringBuilder sb = new StringBuilder();
                                sb.Append("<div class=\"border\" style=\"width:700px\">");
                                sb.Append("  <div class=\"partTitle\" >");
                                sb.Append("     <table cellspacing=\"0\" cellpadding=\"0\" height=\"25px\" width=\"100%\">");
                                sb.Append("         <tr>");
                                sb.Append("             <td class=\"partTitleText\">ACE ALLOCATION</td>");
                                sb.Append("         </tr>");
                                sb.Append("     </table>");
                                sb.Append("  </div>");
                                sb.Append("  <div class=\"columnHeader\">");
                                sb.Append("     <table cellspacing=\"0\" cellpadding=\"0\" height=\"25px\" width=\"100%\">");
                                sb.Append("         <tr>");
                                sb.Append("             <td class=\"columnHeaderText\" style=\"margin-top:5px;\">Allocation Information</td>");
                                sb.Append("         </tr>");
                                sb.Append("     </table>");
                                sb.Append("  </div>");
                                sb.Append("  <div class=\"rows\">");
                                sb.Append("     <table cellspacing=\"0\" cellpadding=\"0\" width=\"100%\">");
                                sb.Append("         <tr class=\"row1\">");
                                sb.Append("             <td class=\"rowTextLeft\" width=\"25%\">Allocation Available:</td>");
                                sb.Append("             <td class=\"rowText\" width=\"75%\">" + AllocationAvail + "</td>");
                                sb.Append("         </tr>");
                                sb.Append("         <tr class=\"row2\">");
                                sb.Append("             <td class=\"rowTextLeft\" width=\"25%\">SPR/JDHF Allotment:</td>");
                                sb.Append("             <td class=\"rowText\" width=\"75%\">" + ConvertToAllocation(DrACE["SPRAmount"].ToString()) + "</td>");
                                sb.Append("         </tr>");
                                sb.Append("         <tr class=\"row1\">");
                                sb.Append("             <td class=\"rowTextLeft\" width=\"25%\">SPR Source:</td>");
                                sb.Append("             <td class=\"rowText\" width=\"75%\">" + DrACE["SPRSource"] + "</td>");
                                sb.Append("         </tr>");
                                //sb.Append("         <tr class=\"row2\">");
                                //sb.Append("             <td class=\"rowTextLeft\" width=\"25%\">TEV:</td>");
                                //sb.Append("             <td class=\"rowText\" width=\"75%\">" + ConvertToAllocation(DrACE["EstVal"].ToString()) + "</td>");  //); + DrACE["SPRSource"] + "</td>");
                                //sb.Append("         </tr>");
                                sb.Append("         <tr class=\"row2\">");
                                sb.Append("             <td class=\"rowTextLeft\" width=\"25%\">Allocation Comments:</td>");
                                sb.Append("             <td class=\"rowText\" width=\"75%\">" + DrACE["AllocationComments"] + "</td>");
                                sb.Append("         </tr>");
                                sb.Append("     </table>");
                                sb.Append("  </div>");
                                sb.Append("  <div class=\"columnHeader\">");
                                sb.Append("     <table cellspacing=\"0\" cellpadding=\"0\" height=\"25px\" width=\"100%\">");
                                sb.Append("         <tr>");
                                sb.Append("             <td class=\"rowTextTitle\" width=\"21%\">Type</td>");
                                sb.Append("             <td class=\"rowTextTitle\" width=\"20%\">Source</td>");
                                sb.Append("             <td class=\"rowTextTitle\" width=\"20%\">FY</td>");
                                sb.Append("             <td class=\"rowTextTitle\" width=\"20%\">$ Amount</td>");
                                sb.Append("             <td width=\"19%\"></td>");
                                sb.Append("         </tr>");
                                sb.Append("     </table>");
                                sb.Append("  </div>");
                                sb.Append("  <div class=\"rows\">");
                                sb.Append("     <table cellspacing=\"0\" cellpadding=\"0\" width=\"100%\">");

                                if (DvAllocation != null)
                                
                                    Boolean row1 = true;
                                    int i = 1;
                                    LiteralControl lc2 = new LiteralControl();

                                    foreach (DataRowView DvAllocationRow in DvAllocation)
                                    
                                        if (row1)
                                        
                                            sb.Append("         <tr class=\"row1\">");
                                            row1 = false;
                                        
                                        else
                                        
                                            sb.Append("         <tr class=\"row2\">");
                                            row1 = true;
                                        


                                        sb.Append("             <td class=\"rowText\" width=\"21%\">" + DvAllocationRow["AllocationType"].ToString() + "</td>");
                                        sb.Append("             <td class=\"rowText\" width=\"20%\">" + DvAllocationRow["AllocationSourceName"].ToString() + "</td>");
                                        sb.Append("             <td class=\"rowText\" width=\"20%\">" + DvAllocationRow["FYTxt"].ToString() + "</td>");
                                        sb.Append("             <td class=\"rowText\" width=\"20%\">" + ConvertToAllocation(DvAllocationRow["Amount"].ToString()) + "</td>");
                                        string querystring = "?ACEID=" + DvAllocationRow["ACEID"].ToString() + "&ACEAllocationID=" + DvAllocationRow["ACE_AllocationID"].ToString();
                                        if (enableStatus)
                                        
                                            m_NewAllocation_Button = new Button();
                                            m_NewAllocation_Button.Text = "Edit Allocation";
                                            //m_NewAllocation_Button.Style = "font-size:8pt;font-family:Verdana,sans-serif";
                                            //m_NewAllocation_Button.Width = 80;
                                            //m_NewAllocation_Button.Height = 21;
                                            m_NewAllocation_Button.CssClass = "plainButton";
                                            m_NewAllocation_Button.ID = "NewAllocationButton" + i;
                                            m_NewAllocation_Button.Attributes.Add("OnClick", "window.open('../_layouts/GIK30/EditAllocation.aspx" + querystring + "');");
                                            //string[] statusArray = new string[]  "Owner", "SiteAdmin" ;
                                            m_NewAllocation_Button.Enabled = enableStatus;
                                            //m_NewAllocation_Button.Visible = enableStatus;

                                            sb.Append("             <td width=\"19%\" align=\"right\" style=\"padding-right:20px\">");
                                            lc2 = new LiteralControl(sb.ToString());
                                            Controls.Add(lc2);
                                            Controls.Add(m_NewAllocation_Button);
                                            sb = new StringBuilder();
                                            sb.Append("</td>");
                                        
                                        else
                                            sb.Append("             <td width=\"19%\"></td>");
                                        //sb.Append("             <td width=\"19%\"><input TYPE=\"button\" VALUE=\"Edit Allocation\" style=\"font-size:8pt;font-family:Verdana,sans-serif\" />");
                                        sb.Append("             </td>");
                                        sb.Append("         </tr>");
                                        i++;
                                    
                                
                                else
                                
                                    sb.Append("     <tr class=\"row1\"><td class=\"rowText\" width=\"100%\">Error Reading from Database</td></tr>");
                                
                                sb.Append("     </table>");
                                sb.Append("  </div>");
                                sb.Append("  <table cellspacing=\"0\" cellpadding=\"0\" style=\"margin-left:9px; margin-top:1px; margin-right:9px\">");
                                sb.Append("     <tr class=\"total\">");
                                sb.Append("         <td width=\"555px\" style=\"vertical-align:middle\">EV on Allotment: " + ConvertToAllocation(DrACE["EstVa"].ToString()) + "</td>");
                                sb.Append("         <td align=\"right\" style=\"padding-right:5px\">");
                                LiteralControl lc = new LiteralControl(sb.ToString());
                                Controls.Add(lc);

                                m_NewAllocation_Button = new Button();
                                m_NewAllocation_Button.Text = "Add New Allocation";
                                //m_NewAllocation_Button.Style = "font-size:8pt;font-family:Verdana,sans-serif";
                                //m_NewAllocation_Button.Width = 80;
                                //m_NewAllocation_Button.Height = 21;
                                m_NewAllocation_Button.CssClass = "plainButton";
                                m_NewAllocation_Button.ID = "NewAllocationButton";
                                m_NewAllocation_Button.Attributes.Add("OnClick", "window.open('../_layouts/GIK30/EditAllocation.aspx?ACEID=" + ACEID + "');");
                                //string[] statusArray = new string[]  "Owner", "SiteAdmin" ;
                                m_NewAllocation_Button.Enabled = enableStatus;
                                //m_NewAllocation_Button.Visible = enableStatus;
                                Controls.Add(m_NewAllocation_Button);

                                sb = new StringBuilder();
                                sb.Append("</td>");
                                sb.Append("     </tr>");
                                sb.Append("  </table>");
                                sb.Append("</div>");
                                lc = new LiteralControl(sb.ToString());
                                Controls.Add(lc);
                            
                        
                        catch (Exception ex)
                        
                            HandleException(ex);
                            IDEErrLogging.LogError(new IDEException("ACE Allocation: Error on ACE: " + ACEID.ToString(), ex), true, false, SPContext.Current.Web);
                        
                    
                
            
        

        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        
            if (!_error)
            
                try
                
                    base.OnLoad(e);
                    this.EnsureChildControls();
                    // Your code here...
                
                catch (Exception ex)
                
                    HandleException(ex);
                
            
        

        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException(Exception ex)
        
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        

        protected void m_NewAllocation_Button_Click(object sender, EventArgs e)
        
            Page.Response.Redirect("EditAllocation.aspx?ACEID=" + Page.Request["ACEID"]);
        

        private string ConvertToAllocation(string stramount)
        
            // Convert the real number to a $ format
            double amount = 0.0;
            if (!String.IsNullOrEmpty(stramount))
                amount = Convert.ToDouble(stramount);
            return string.Format("0:C", amount);
        
    

【问题讨论】:

【参考方案1】:

我得出的解决方案是:

首先我在表格代码之前添加了一个新的文字控件(我有字段并想添加控件):

LiteralControl lc3 = new LiteralControl();

然后,我将 LC 包含在我想将只读值更改为控件的表中,例如:

   sb.Append("             <td class=\"rowTextLeft\" width=\"25%\">SPR/JDHF Allotment:</td>");
   sb.Append("             <td class = \"rowText\" td width=\"75%\">"); 
                                                   lc3 = new LiteralControl(sb.ToString()); 
                                                   Controls.Add(lc3); 
                                                   TextBox JDHFTxt = new TextBox(); 
                                                   JDHFTxt.ID = "txtJDHF"; 
                                                   JDHFTxt.Enabled = false; 
                                                   JDHFTxt.Value = ConvertToAllocation(DrACE["SPRAllotment"].ToString()); 
                                                   Controls.Add(JDHFTxt); 
                                                   sb = new StringBuilder();
   sb.Append("</td>");

【讨论】:

以上是关于如何将控件添加到 Web 部件(SharePoint、C#)?的主要内容,如果未能解决你的问题,请参考以下文章

将内容编辑器 Web 部件添加到 sharepoint 2010 用户控件

Sharepoint 将自定义控件添加到 Web 部件错误

在 Sharepoint 2013 中将用户控件添加到 Web 部件

CSS 规则可以动态添加到 Sharepoint 2010 Web 部件控件吗?

ASP.NET 按钮不呈现 ID - Sharepoint Web 部件

如何将Web部件区域添加到SharePoint Wiki页面?