Wednesday, November 14, 2012

Printing content of a particular area of a page through Java Script function.

This is the way to print content of a particular div through this function. Very basic but important :

function PrintContent(ctrl) {
        var DocumentContainer = ctrl;
        var WindowObject = window.open('', "TrackHistoryData",
            "width=420,height=225,top=250,left=345,toolbars=no,scrollbars=yes,status=no,resizable=no");
        WindowObject.document.write(DocumentContainer.innerHTML);
        WindowObject.document.close();
        WindowObject.focus();
        WindowObject.print();
        WindowObject.close();
    }


You need to put this iframe for better preview..

<iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute">
</iframe>


This is function for whole Page :

 function printPage() {
        var content = document.getElementById("Your Div ID");
        var pri = document.getElementById("ifmcontentstoprint").contentWindow;
        pri.document.open();
        pri.document.write(content.innerHTML);
        pri.document.close();
        pri.focus();
        pri.print();
    }

Friday, November 2, 2012

How to query two or more columns of SharePoint list with multiple Values.

Here I am going to explain a you a way to create a dynamic query which deals with multiple values of two fields(Columns). There are other way of doing it to do it through LINQ but that would be heavy because you have to use for each loop for the purpose.

I will do it for two list of string values collection for two columns. I am considering AND operation between columns and OR between all values for columns. I will divide into three function for clarity. However I and II are same except its filed name, you can modify it as per your need. III function would be combine both these queries with an AND operator.

1. First we will create dynamic query for Column1:

 public StringBuilder GetQueryForColumn1(List<string> Values1)
        {
            StringBuilder stbQuery = new StringBuilder();
            if (Regions.Count > 0)
            {
                bool first = true;
                    foreach (string Value in Values1)
                    {

                        if (first)
                        {
                            stbQuery.Append("<Eq><FieldRef Name='Column1' /><Value Type='Text'>").Append(Value .Trim()).Append("</Value></Eq>");
                            first = false;
                        }
                        else
                        {
                            string formatedQuery = stbQuery.ToString();
                            StringBuilder objNew = new StringBuilder();
                            objNew.Append("<Or>");
                            objNew.Append("<Eq><FieldRef Name='Column1' /><Value Type='Text'>").Append(Value .Trim()).Append("</Value></Eq>");
                            objNew.Append(formatedQuery);
                            objNew.Append("</Or>");
                            stbQuery = objNew;
                        }
                }
            }
            return stbQuery;
        }


2. Now we will create dynamic query for Column2:

 public StringBuilder GetQueryForColumn2(List<string> Values2)
        {
            StringBuilder stbQuery = new StringBuilder();
            if (Regions.Count > 0)
            {
                bool first = true;
                    foreach (string Value in Values2)
                    {

                        if (first)
                        {
                            stbQuery.Append("<Eq><FieldRef Name='Column2' /><Value Type='Text'>").Append(Value .Trim()).Append("</Value></Eq>");
                            first = false;
                        }
                        else
                        {
                            string formatedQuery = stbQuery.ToString();
                            StringBuilder objNew = new StringBuilder();
                            objNew.Append("<Or>");
                            objNew.Append("<Eq><FieldRef Name='Column2' /><Value Type='Text'>").Append(Value .Trim()).Append("</Value></Eq>");
                            objNew.Append(formatedQuery);
                            objNew.Append("</Or>");
                            stbQuery = objNew;
                        }
                }
            }
            return stbQuery;
        }


3. Then we will put this into a common function and concatenate  it : 

 public StringBuilder GetQueryForBothColumn1AndColumn2(List<string> Regions, List<string> OfficerTitles)
        {
            StringBuilder stbAllQuery = new StringBuilder();
            stbAllQuery.Append("<Where><And>");
            stbAllQuery.Append( GetQueryForColumn1(Values1));
            stbAllQuery.Append( GetQueryForColumn2(Values2));
            stbAllQuery.Append("</And></Where>");
            return stbAllQuery;
        }

 
Now this query you can use to query on this on your chunk of selected choices in a single query to list. you can do it for more than two columns as well but that would need a bit effort and change in  GetQueryForBothColumn1AndColumn2 function.




Wednesday, October 31, 2012

How to manage and query items in folders of SharePoint Lists pro-grammatically in C#.

Here I am going to provide you very simple way of managing your SharePoint List Items in Folders. In this way we will first check that folder with this name exists or not. If it exists then it will insert item in that folder and if not then it will create a new folder of this name and put item inside this newly created folder. 

At first we need to include this method in our project to check that particular folder exists or not :

 public static bool FolderExists(string url, SPWeb web)
        {
            try
            {
                if (web.GetFolder(url).Exists)
                {
                    return true;
                }
                return false;
            }
            catch (ArgumentException ex)
            {
                Logger.Write(ex);
                return false;
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return false;
            }
        }


This methods will check that a folder with the supplied parameters exists or not. And then add item as per values given in corresponding folder OR if does not exists will create a new one  and then add item as per values given in corresponding folder.  

public void UpdateDemoFolderInListA(SPWeb objSPWeb, string strDemo)
        {
            if (objSPWeb != null)
            {
                SPList objSPListListA = objSPWeb.Lists.TryGetList("ListA");
                if (objSPListSavedSearch != null)
                {
                    SPFolder spFolder;
                    if (FolderExists(objSPWeb.ServerRelativeUrl + "/Lists/ListA/" + strDemo, spWeb))
                    {
                        spFolder = spWeb.GetFolder(objSPWeb.ServerRelativeUrl + "/Lists/ListA/" + strDemo);
                    }
                    else
                    {
                        SPListItem newFolder = objSPListSavedSearch.Items.Add(spWeb.ServerRelativeUrl + "/" + objSPListListA.RootFolder.Url, SPFileSystemObjectType.Folder, strDemo);
                        newFolder.Update();
                        spFolder = spWeb.GetFolder(spWeb.ServerRelativeUrl + "/Lists/ListA/" + strDemo);
                    }
                        SPListItem item = objSPListListA.Items.Add(spFolder.ServerRelativeUrl, SPFileSystemObjectType.File);
                        item["Column1"] = Value1;
                        item["Column2"] = Value2;
                        item["Column3"] = Value3;
                        item.Update();
                    }
                }
            }
        }


You can use this approach to extend functionality such as to add item in some restriction such as maximum no. of items in the folder or date wise folder or user logged in folder items update.Anyways querying for item inside a particular folder with defined URL will a performance boost.  Hope it will help.

Tuesday, October 30, 2012

How to add a border less poopup in an asp.net or SharePoint Page.

It is quite tedious to add popup in your page without any border. And more than that if you have to transfer a lot of information. Sometimes we need to add a new Page in our project just for adding a very simple popup which contains a text box only. However putting all theses you can not get rid of windows default close and minimize button. So I have done this through putting a div and then setting its z-index style. Through which It will look like a popup.

Here are the steps to integrate this solution into your page.

Code need to put into .aspx or .ascx file :-

Code to put add a panel and controls : 

 <asp:Panel runat="server" ID="pnlPopupContainer" CssClass="positionSetter">
        <table width="100%">
            <tr style="width: 100%">
                <td style="text-align: left; vertical-align: middle; width: 300px; padding-left: 10px;">
                    <asp:TextBox runat="server" ID="txtBox1" Width="275px"></asp:TextBox>
                </td>
                <td style="vertical-align: middle; width: 300px;">
                    <asp:LinkButton runat="server" Text="
Save Search" ID="lnkBtn1"                                  OnClientClick="HideMainPanel()" OnClick="lnkBtn1_Click"></asp:LinkButton>
                </td>
            </tr>
        </table>
    </asp:Panel>


 This is the link on which click popup will be opened. It can be a button or anything you want.
<a href='#' onclick='ShowPanel()'><b>Open Popup </b></a>

 Styles :  

      .positionSetter       
      {
            position: absolute;
            left: 275px;
            top: 425px;
            width: 400px !important;
            height: 35px !important;
            text-align: center;
            z-index: 1000;
            background-color: #4f81bc !important;
            visibility: hidden;
        }

This style class will play a very crucial role in its positioning.  Left and top attribute will set its horizontal position in page, z-index will position its over page and give a popup feel, width and height will decide popup width and height. 

JavaScript :
This java script functions will show and hide of our div(popup).

function HideMainPanel() {
            el = document.getElementById('<%=
pnlPopupContainer.ClientID%>');
            if (el != null) {
                el.style.visibility = "hidden";
            }
        }

        function ShowPanel() {
            el = document.getElementById('<%=
pnlPopupContainer.ClientID%>');
            if (el != null) {
                el.style.visibility = "visible";
            }

        }


Through this code you can view it in this way.



And you can customize it as per your requirement further.

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.