Friday, October 19, 2012

How to bubble a user control event in its calling pages or webparts.

This is a user control which contains a Drop Down list and an event


UserControl.ascx contents will be like this : 

<%@ Control Language="C#" AutoEventWireup="true" Inherits="NameSpaceName.ClassName, NameSpaceName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=74a8568657e011e0" %>
.drp-color
{
    color:#7d99c1;
    font-family:Calibri;
    font-size: 8pt;
    width:150px;
}
</style>
<asp:Panel runat="server" ID="mainPanel">
 <asp:DropDownList ID="drpList" runat="server" AutoPostBack="true"  CssClass="drp-color" OnSelectedIndexChanged="drpList_SelectedIndexChanged">
</asp:DropDownList>
</asp:Panel>


UserControl.ascx.cs contents will be like this :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Web.UI;
using Microsoft.SharePoint;

namespace NameSpaceName
{
    public partial class ClassName: System.Web.UI.UserControl
    {
        public string TextColumnName { get; set; }
        public string IdColumnName { get; set; }
        public string ListName { get; set; }
     
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PopulateDropDown();
            }
          
        }

        public void PopulateDropDown()
        {
            try
            {
                DataTable dtResult;
                using (SPSite spSite = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        dtResult = GetListValues(spWeb);
                        drpList.DataSource = dtResult;
                        drpList.DataValueField = this.IdColumnName;
                        drpList.DataTextField = this.TextColumnName;
                        drpList.DataBind();
                        ListItem objItem = new ListItem("View All", "0");
                        drpList.Items.Insert(0, objItem);

                        //if (this.drpList.Items.Count > 0)
                        //{
                        //    this.drpList.Items[0].Selected = true;
                        //    this.OnDropDownListSelectionChanged();
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public DataTable GetListValues(SPWeb spWeb)
        {
            SPList lstValues = GetList(this.ListName, spWeb);
            if (null != lstValues)
            {
                if (lstValues.ItemCount > 0)
                    return lstValues.Items.GetDataTable();
                else
                    return null;
            }

            return null;
        }

        public SPList GetList(string listName, SPWeb spWeb)
        {
            SPList spList = null;

            if (null != spWeb)
            {
                try
                {
                    spList = spWeb.Lists[listName];
                }
                catch (Exception)
                {
                    spList = null;
                }
            }

            return spList;
        }

        public void drpList_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.OnDropDownListSelectionChanged(sender,e);

        }

        # region Event Section
     
       public delegate void DropDownSelectionDelegate(object sender, EventArgs e);
       protected event DropDownSelectionDelegate drpListselectionChanged;

        public event DropDownSelectionDelegate DropDownListSelectionChanged
        {
            add
            {
                this.drpListselectionChanged += value;
            }
            remove
            {
                this.drpListselectionChanged -= value;
            }
        }
        public virtual void OnDropDownListSelectionChanged(object sender, EventArgs e)
        {
          
            if (this.drpListselectionChanged != null)
                this.drpListselectionChanged(sender,e);
        }
        # endregion
    }
}


Now in the Web part/Page in which you are using this control or want to trap this user control events. In this case its a visual web part (It will be inside another user control) will be like this :
 UserControlABC.ascx :

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserControlA.ascx.cs"
    Inherits="NameSpace.ClassName.UserControlA" %>
<%@ Register Src="/_controltemplates/Project1/SPDropDownControl.ascx" TagPrefix="SAUserControl"
    TagName="SPDropDownList" %>
    <style type="text/css">
        .pnlHorizontal
        {
        width:100%           
        }
    </style>
<asp:Panel runat="server" ID="pnlHorizontal" Visible="false" CssClass="pnlHorizontal">
    <table width="100%">
        <tr>
            <td>
                <font style='font-family: Calibri !important; color: #C0C0C0 !important; font-size: 14pt!important; padding-left:50px; width:30%;'>
                    B :</font>
            </td>
            <td >
                <font style='font-family: Calibri !important; font-size: 8 !important; color: #58443B !important; width:30%;'>
                    D : </font></br>
                <SAUserControl:SPDropDownList runat="server" ID="uscH1" OnDropDownListSelectionChanged="ucListControl1_DropDownListSelectionChanged"
                    TextColumnName="Title" IdColumnName="ID" ListName="Channel" />
            </td>
            <td >
                <font style='font-family: Calibri !important; font-size: 8 !important; color: #58443B !important; width:30%;'>
                    H : </font></br><SAUserControl:SPDropDownList runat="server" ID="uscH2"
                        OnDropDownListSelectionChanged="ucListControl1_DropDownListSelectionChanged"
                        TextColumnName="Title" IdColumnName="ID" ListName="Topic" />
            </td>
            <td>
                <font style='font-family: Calibri !important; font-size: 8 !important; color: #58443B !important; width:30%; padding-right:100px;'>
                   I : </font></br><SAUserControl:SPDropDownList runat="server" ID="uscH3"
                        OnDropDownListSelectionChanged="ucListControl1_DropDownListSelectionChanged"
                        TextColumnName="Name" IdColumnName="ID" ListName="SMEProfile" />
            </td>
        </tr>
    </table>
</asp:Panel>
<asp:Panel runat="server" ID="pnlVertical" Visible="false">
    <table>
        <%--<tr>
            <td class='tc-VerticalSMEHeading'>
                Find eXpert Knowledge by:
            </td>
        </tr>--%>
        <tr>
            <td>
                <font style='font-family: Calibri !important; font-size: 8pt !important; color: black !important;'>
                    A:</font></br><SAUserControl:SPDropDownList runat="server" ID="uscV2" OnDropDownListSelectionChanged="ucListControl1_DropDownListSelectionChanged"
                    TextColumnName="Title" IdColumnName="ID" ListName="Channel" />
            </td>
            <td>
        </tr>
        <tr>
            <td>
                <font style='font-family: Calibri !important; font-size: 8pt !important; color: black !important;'>
                    F :</font></br><SAUserControl:SPDropDownList runat="server" ID="uscV1"
                        OnDropDownListSelectionChanged="ucListControl1_DropDownListSelectionChanged"
                        TextColumnName="Title" IdColumnName="ID" ListName="Topic" />
            </td>
        </tr>
        <tr>
            <td>
                <font style='font-family: Calibri !important; font-size: 8pt !important; color: black !important;'>
                    E : </font></br><SAUserControl:SPDropDownList runat="server" ID="uscV3"
                        OnDropDownListSelectionChanged="ucListControl1_DropDownListSelectionChanged"
                        TextColumnName="Name" IdColumnName="ID" ListName="SMEProfile" />
            </td>
        </tr>
    </table>
</asp:Panel>



UserControlABC.ascx.cs:

namespace NameSpace
{
    public partial class UserControlABC : UserControl
    {
        public bool Horizontal { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
          
        }

        protected void ucListControl1_DropDownListSelectionChanged(object sender, EventArgs e)
        {
            DropDownList ddlCurrent = (DropDownList)sender;
            string selectedID = ddlCurrent.SelectedValue;
            switch (((System.Web.UI.WebControls.ListControl)(sender)).Parent.Parent.ID)
            {
                case "A":
                    Response.Redirect(SPContext.Current.Web.Url + string.Format("/Pages/rets.aspx?ID={0}&Mode=Channel",selectedID));
                    break;
                case "B":
                    Response.Redirect(SPContext.Current.Web.Url + string.Format("/Pages/hyut.aspx?ID={0}&Mode=Topic", selectedID));
                    break;
                case "F":
                    Response.Redirect(SPContext.Current.Web.Url + string.Format("/Pages/kjil.aspx?ID={0}", selectedID));
                    break;
                case "C":
                    Response.Redirect(SPContext.Current.Web.Url + string.Format("/Pages/ghi.aspx?ID={0}&Mode=Channel",selectedID));
                    break;
                case "D":
                    Response.Redirect(SPContext.Current.Web.Url + string.Format("/Pages/mno.aspx?ID={0}&Mode=Topic", selectedID));
                    break;
                case "E":
                    Response.Redirect(SPContext.Current.Web.Url + string.Format("/Pages/abs.aspx?ID={0}", selectedID));
                    break;
            }
        }
    }
}




Now you can trap this event as per cases in which you have used it.
 

Thursday, October 18, 2012

How to insert an image, page, video or file in a SharePoint site Document Library through a feature.

Suppose you want to upload an image or any file on a site document library on feature activated. It will get uploaded on that gallery and then you can use this image path in your code. Now you can change image without changing its name and can change it. Steps are as follows:

Steps for adding an image in Document Library:

1.) First you need to open a SharePoint type project in Visual Studio 2010. Now add a new Module to project and name it as "SiteCollectionImages" and within it. Now add a new folder within this module and rename this folder as "Document Library Name". Put this image inside this folder.

2.) Now in Elements.xml file of module and made elements.xml file entry should be like this :

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module  Name="SiteCollectionImages" Url="SiteCollectionImages" >
      <File Path="
Document Library Name/Default.jpg" Url="Default.jpg" Type="GhostableInLibrary" />
  </Module>
</Elements>


Here SiteCollectionImages is the Module Name and document library name is name of the doc lib in which you want to keep this image or file.

3.) Now right click on this particular image and select properties and in properties select its Deployment Location. In deployment location path should be like this "Document Library Name/". Now save it.

4.) Now activate the feature added by default and this image will be uploaded into your doc library. You can upload any static file (which do cont contains code) like this and then use it across SharePoint site.



Wednesday, October 17, 2012

How to add all different type of columns to a sharepoint 2010/2007 list and views.

This post will tell that how to add different types of columns to a SharePoint List and its views 2007/2010 through code. It will tell how to add all  kinds of columns in an already existing list and also their views. You can put this code inside a feature or in whatever context you need it :

Adding a Single Line of Text column :


private static void AddSingleLineOfTextFieldToList(SPList objSPList, string FieldName)
        {
            if (objSPList != null)
            {
                if (!objSPList.Fields.ContainsField(FieldName))
                {
                    objSPList.Fields.Add(FieldName, SPFieldType.Text, false);
                }
            }
        }

Adding a Multiple Line of Text column : 

 private static void AddMultipleLineOfTextFieldToList(SPList objSPList, string FieldName)
        {
            if (objSPList != null)
            {
                if (!objSPList.Fields.ContainsField(FieldName))
                {
                    objSPList.Fields.Add(FieldName, SPFieldType.Note, false);
                }
            }
        }

Adding a Rich Text Type of  column :

private static void AddRichTextFieldToList(SPList objSPList, string FieldName)
        {
            if (objSPList != null)
            {
                if (!objSPList.Fields.ContainsField(FieldName))
                {
                    objSPList.Fields.Add(FieldName, SPFieldType.Note, true);
                    SPFieldMultiLineText field = (SPFieldMultiLineText)objSPList.Fields[FieldName];
                    field.RichText = true;
                    field.RichTextMode = SPRichTextMode.Compatible;
                    field.Update();
                }
            }
        }


Adding a Calculated Type of Column :

 private static void AddCalculatedFieldToList(SPList objSPList, string FieldName, string Formula, SPFieldType OutputType)
        {
            if (objSPList != null)
            {
                if (!objSPList.Fields.ContainsField(FieldName))
                {
                    objSPList.Fields.Add(FieldName, SPFieldType.Calculated, false);
                    SPFieldCalculated CalcField = (SPFieldCalculated)objSPList.Fields[FieldName];
                    CalcField.OutputType = OutputType;
                    CalcField.Formula = Formula;
                    CalcField.Update();
                }
            }
        }

Adding a DateTime Type column:

private static void AddDateTimeColumn(SPList objSPList, string columnName)
        {
            if (objSPList != null && columnName != null)
            {
                if (!objSPList.Fields.ContainsField(columnName))
                {
                    /* add a new choice field */
                    objSPList.Fields.Add(columnName, SPFieldType.DateTime, false);
                    objSPList.Update();
                    /* get the newly added choice field instance */
                    SPFieldDateTime objSPField = (SPFieldDateTime)objSPList.Fields[columnName];
                    objSPField.DisplayFormat = SPDateTimeFieldFormatType.DateTime;
                    objSPField.Update();
                    /* finally update list */
                    objSPList.Update();
                }
            }
        }

Adding a People and Group Type of Column :

private static void AddPeopleandGroupColumnToList(SPWeb objSPWeb, string listName, string columnName)
        {
            if (objSPWeb != null)
            {
                SPList objSPList = objSPWeb.Lists[listName];
                if (objSPList != null && (!string.IsNullOrEmpty(columnName)))
                {
                    if (!objSPList.Fields.ContainsField(columnName))
                    {
                        objSPList.Fields.Add(columnName, SPFieldType.User, false);
                        SPFieldUser userField = (SPFieldUser)objSPList.Fields[columnName];
                        userField.LookupField = "Name";
                        userField.Update();
                        objSPList.Update();
                        AddFieldToListDefaultView(objSPList, columnName);
                    }
                }
            }
        }

Adding a Choice Field Type of Columns:  

private static void AddChoiceColumn(SPList objSPList, string columnName, StringCollection strChoices, string defaultValue)
        {
            if (objSPList != null && columnName != null)
            {
                if (!objSPList.Fields.ContainsField(columnName))
                {
                    /* add a new choice field */
                    objSPList.Fields.Add(columnName, SPFieldType.Choice, false);
                    objSPList.Update();
                    /* get the newly added choice field instance */
                    SPFieldChoice objSPField = (SPFieldChoice)objSPList.Fields[columnName];
                    /* set field format type i.e. radio / dropdown */
                    objSPField.EditFormat = SPChoiceFormatType.Dropdown;
                    /* set the choice strings and update the field */
                    if (strChoices.Count > 0)
                    {
                        for (int iCounter = 0; iCounter < strChoices.Count; iCounter++)
                        {
                            objSPField.Choices.Add(strChoices[iCounter]);
                        }
                    }
                    objSPField.DefaultValue = defaultValue;
                    objSPField.Update();
                    /* finally update list */
                    objSPList.Update();
                }
            }
        }

Add a LookUp Type of column :

private static void AddLookUpColumn(SPWeb objSPWeb, SPList objSPList, string LookupSourceListName, string columnName, string sourceColumnName)
        {
            if (objSPWeb != null)
            {
                /*create lookup type new column called "Lookup Column"*/
                SPList objLookupSourceList = objSPWeb.Lists[LookupSourceListName];
                if (!objSPList.Fields.ContainsField(columnName))
                {
                    objSPList.Fields.AddLookup(columnName, objLookupSourceList.ID, false);
                    SPFieldLookup lkp = (SPFieldLookup)objSPList.Fields[columnName];
                    lkp.LookupField = objLookupSourceList.Fields[sourceColumnName].InternalName;
                    lkp.Update();
                }
            }
        }

Add a Column to particular List View

private static void AddColumnToView(SPList objSPList string ViewName, string columnName)
        {
            if (objSPList != null && columnName != null)
            {
                if (objSPList.Views[ViewName] != null)
                {
                    SPView objSPListCatalogView = objSPList.Views[ViewName];
                    if (!objSPListView.ViewFields.Exists(columnName))
                    {
                        objSPListView.ViewFields.Add(columnName);
                        objSPListView.Update();
                    }
                    objSPList.Update();
                }
            }
        }

In this way you will be able to add all type of columns and then them to view of a SharePoint List. All you need to do is to add these methods in your and pass asked parameter.