Wednesday, March 13, 2013

Dynamically changing DataList Template in VisaulWebPart

This visual webpart is using a data list to display two different template data. The item template design would change based on one parameter. Additionally use of page data source is also displayed

http://apartha77.blogspot.in/2012/05/dynamically-changing-datalist-template.html


The ASCX –
Removed the Drop down code:
<table class="TableHeader">
    <tr class="Content">
        <td align="left" valign="middle" class="KnowledgeHeading_LV2">
            Office Template Index
        </td>
        <td class="DLHeader" style="width: 30%; text-align: right; padding-right: 30px; vertical-align: middle;
            padding-top: 10px">
            <asp:Button ID="btnPrev" runat="server" Text="<<" OnClick="btnPrev_Click" />
            <asp:Label ID="lblCurrentPage" runat="server" Text="" />
            <asp:Button ID="btnNext" runat="server" Text=">>" OnClick="btnNext_Click" />
        </td>
    </tr>
</table>

<table style="width:857px">
    <tr>
        <td>
            <asp:DataList ID="dlOfficeTemplate" runat="server" GridLines="Both">
                <ItemTemplate>
                    <asp:Literal ID="ltlTemplate" runat="server" Text='<%#GetItemTemplate((DataRowView)Container.DataItem) %>' />
                </ItemTemplate>
            </asp:DataList>
        </td>
    </tr>
    <tr>
        <td align="center" style="font-size: 12px; text-align:center; padding-top:10px;">
            <asp:Label ID="lblMsg" runat="server" Visible="false"></asp:Label>
        </td>
    </tr>
</table>

The CS page
Page Data Source:
#region Page Data Source
        PagedDataSource pagedDataSource = new PagedDataSource();
        int iPageSize = 7;
        public int currentPage
        {
            get
            {
                object o = this.ViewState["_currentPage"];
                if (o == null)
                    return 0;
                else
                    return (int)o;
            }
            set
            {
                this.ViewState["_currentPage"] = value;
            }
        }
        #endregion


#region Paging Button Click Next - Previous
        protected void btnPrev_Click(object sender, EventArgs e)
        {
            currentPage -= 1;
            PopulateOfficeTemplates(ddlCompanyTemplates.SelectedItem.Text);
        }

        protected void btnNext_Click(object sender, EventArgs e)
        {
            currentPage += 1;
            PopulateOfficeTemplates(ddlCompanyTemplates.SelectedItem.Text);
        }
#endregion



The rest of the code:
#region Page Load
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                PopulateDDLCompanyList();
        }
        #endregion
#region Populate DDL Company Template
        /// <summary>
        /// Populate templates list in dropdown control
        /// </summary>
        protected void PopulateDDLCompanyList()
        {
            try
            {
                var parent = (ListView_MSOfficeTemplatesLogo)Parent;
                if (parent.SiteURL != null && parent.LibraryName != null)
                {
                    string siteURL = SPContext.Current.Site.Url + parent.SiteURL;
                    string libraryName = parent.LibraryName;
                    using (SPSite site = new SPSite(siteURL))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPList spListPress = web.Lists[libraryName];
                            SPQuery sQuery = new SPQuery();
                            sQuery.Query = "<OrderBy><FieldRef Name='Title' Ascending='False'></FieldRef></OrderBy>";
                            DataTable dtCompany = spListPress.GetItems(sQuery).GetDataTable();
                            if (dtCompany != null && dtCompany.Rows.Count > 0)
                            {
                                ddlCompanyTemplates.DataSource = dtCompany.DefaultView.ToTable(true,"Title");
                                ddlCompanyTemplates.DataTextField = "Title";
                                ddlCompanyTemplates.DataValueField = "Title";
                                ddlCompanyTemplates.DataBind();
                                PopulateOfficeTemplates(dtCompany.Rows[0]["Title"].ToString().Trim());
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Microsoft.Office.Server.Diagnostics.PortalLog.LogString("Check OfficeTemplatesLogo WebPart - Populate DDL :" + ex.Message);
                throw new SPException("Check OfficeTemplatesLogo WebPart - Populate DDL");
            }
        }
        #endregion

        #region DDL Company Templates Selected Index Change
        /// <summary>
        /// Selected index changed event for company templates
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlCompanyTemplates_SelectedIndexChanged(object sender, EventArgs e)
        {
            currentPage = 0;
            PopulateOfficeTemplates(ddlCompanyTemplates.SelectedItem.Text);
        }
        #endregion

        #region Populate MS Office Templates
        /// <summary>
        /// Populate Office Templates
        /// </summary>
        /// <param name="strCompanyTemplates"></param>
        protected void PopulateOfficeTemplates(string strCompanyTemplates)
        {
            try
            {
                var parent = (ListView_MSOfficeTemplatesLogo)Parent;
                if (parent.SiteURL != null && parent.LibraryName != null)
                {
                    string siteURL = SPContext.Current.Site.Url + parent.SiteURL;
                    string libraryName = parent.TemplatelibraryName;
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite elevatedSite = new SPSite(siteURL))
                        {
                            using (SPWeb elevatedWeb = elevatedSite.OpenWeb())
                            {
                                SPList spListDocumentLib = elevatedWeb.Lists[libraryName];
                                SPQuery sQuery = new SPQuery();
                                if (strCompanyTemplates == "Company Logo")
                                {
                                    iPageSize = 7;
                                    sQuery.Query =
                                    "<Where>" +
                                    "<And>"+
                                         "<Eq><FieldRef Name='IsLogo' /><Value Type='Boolean'>1</Value></Eq>" +
                                         "<Eq><FieldRef Name='CompanyTemplates' /><Value Type='Text'>"+strCompanyTemplates+"</Value></Eq>" +
                                     "</And>" +
                                    "</Where>" +
                                    "<OrderBy><FieldRef  Name='Modified' Ascending='FALSE' /></OrderBy>";
                                }
                                else
                                {
                                    iPageSize = 15;

                                    sQuery.Query =
                                    "<Where>" +
                                     "<And>" +
                                        "<Eq><FieldRef Name='CompanyTemplates'/><Value Type='Text'>" + strCompanyTemplates + "</Value></Eq>" +
                                        "<Eq><FieldRef Name='IsLogo' /><Value Type='Boolean'>0</Value></Eq>" +
                                     "</And>" +
                                    "</Where>" +
                                    "<OrderBy><FieldRef  Name='Modified' Ascending='FALSE' /></OrderBy>";
                                }

                                DataTable dtItems = spListDocumentLib.GetItems(sQuery).GetDataTable();
                                if (dtItems != null && dtItems.Rows.Count > 0)
                                {
                                    pagedDataSource.DataSource = dtItems.DefaultView;
                                    pagedDataSource.AllowPaging = true;
                                    pagedDataSource.PageSize = iPageSize;
                                    pagedDataSource.CurrentPageIndex = currentPage;
                                    btnPrev.Enabled = (!pagedDataSource.IsFirstPage);
                                    btnNext.Enabled = (!pagedDataSource.IsLastPage);
                                    lblCurrentPage.Text = "Page: " + (currentPage + 1).ToString() + " of "+ pagedDataSource.PageCount.ToString();
                                    dlOfficeTemplate.DataSource = pagedDataSource;
                                    dlOfficeTemplate.DataBind();
                                    lblMsg.Visible = false;
                                }
                                else
                                {
                                    dlOfficeTemplate.DataBind();
                                    lblMsg.Visible = true;
                                    lblMsg.Text = "Not Data Found";
                                }

                            }
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                PortalLog.LogString("Exception OfficeTemplatesLogo WebPart - Populate DataList :" + ex.Message);
                throw new SPException("Check OfficeTemplatesLogo WebPart - Populate DataList");
            }
        }
        #endregion

        #region Data List Protected Methods
        protected string GetImageToDisplayValue(DataRowView oView)
        {
            string strDisplayHTML = string.Empty;
            //strDisplayHTML = oView["LinkFilename"].ToString();
            string strImageFileName = oView["LinkFilename"].ToString();
            var parent = (ListView_MSOfficeTemplatesLogo)Parent;
            string siteURL = SPContext.Current.Site.Url + parent.SiteURL;
            string libraryName = parent.TemplatelibraryName;
            string strImageUrl = siteURL + "/" + libraryName + "/" + strImageFileName;
            return strImageUrl;
        }

        protected string GetItemTemplate(DataRowView oView)
        {
            var parent = (ListView_MSOfficeTemplatesLogo)Parent;
            string siteURL = SPContext.Current.Site.Url + parent.SiteURL;
            string libraryName = parent.TemplatelibraryName;
            string strFilename = oView["LinkFilename"].ToString();
            string strTitle = oView["Title"].ToString();
            string strImageUrl = siteURL + "/" + libraryName + "/" + strFilename;
            string strTemplateText = string.Empty;

            if (ddlCompanyTemplates.SelectedItem.Text == "Company Logo")
            {
                strTemplateText = string.Format(@"
             <table id='tblOfficeTemplateLogo' cellpadding='0' cellspacing='0' width='850px'>
                        <tr style='height:50px;'>
                            <td align='center' style='width: 450px; text-align: center; vertical-align: middle;'>
                              <img id='imgLogo' src='{0}' alt='{1}' Target='_blank' height='44px'/>
                            </td>
                            <td style='width: 400px; text-align:left; vertical-align: middle;'>
                            <a id='hlnkName' ToolTip='{1}' Target='_blank' href='{0}'>{1}</a>
                            </td>
                        </tr>
                    </table>", strImageUrl, strTitle);
            }
            else
            {
                strTemplateText = string.Format(@"
             <table id='tblOfficeTemplate' cellpadding='0' cellspacing='0' width='850px'>
                        <tr style='height:25px;'>
                            <td style='width: 450px; text-align:left; vertical-align: middle;'>
                                <span id='doc'>{0}</span>
                            </td>
                            <td style='width: 400px; text-align:left; vertical-align: middle;'>
                            <a id='hlnkName' ToolTip='{1}' Target='_blank' href='{2}'>{1}</a>
                            </td>
                        </tr>
                    </table>", strFilename, strTitle, strImageUrl);
            }
            return strTemplateText;
        }
        #endregion

Container.DataItem Method returns the expected return html.

No comments:

Post a Comment