Saturday, January 26, 2013

Bind even and Odd SharePoint ListItems Side by Side within a GridView

Bind even and Odd SharePoint ListItems Side by Side within a GridView




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="EOGridViewUserControl.ascx.cs" Inherits="EOGridView.EOGridView.EOGridViewUserControl" %>
<div>&nbsp;</div>
<div>&nbsp;</div>
<div>
<table width="100%" cellpadding="0" cellspacing="0">
<tr><td align="center"><strong>Bind even & Odd SharePoint ListItems Side by Side within a GridView</strong></td></tr>
</table>
</div>
<div>&nbsp;</div>
<div>
<asp:GridView runat="server" ID="dgvEvenOddGridView"
    AutoGenerateColumns="False" Width="100%" BackColor="White"
    BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4"
    EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="OddRecord" HeaderText="Odd Record" />
<asp:BoundField DataField="EvenRecord" HeaderText="Even Record" />
</Columns>
    <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
    <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
    <RowStyle BackColor="White" ForeColor="#330099" />
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
</asp:GridView>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</div>
Ascx.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Security;
using System.Data;
using System.Collections;
namespace EOGridView.EOGridView
{
    public partial class EOGridViewUserControl : UserControl
    {
        ArrayList ArrOdd = new ArrayList();
        ArrayList ArrEven = new ArrayList();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                getData();
            }
        }
        public void getData()
        {
            SPWeb currentWeb = SPContext.Current.Web;
            SPList lst = currentWeb.Lists["Articles"];
            SPListItemCollection myColl = lst.Items;
            if (myColl.Count > 0)
            {
                int i = 0;
                foreach (SPListItem item in myColl)
                {
                    if (i % 2 != 0)
                    {
                        ArrOdd.Add(item.Title.ToString());
                    }
                    else
                    {
                        ArrEven.Add(item.Title.ToString());
                    }
                    i++;
                }
                DataTable dt = new DataTable();
                dt.Columns.Add("OddRecord");
                dt.Columns.Add("EvenRecord");
                for (int k = 0; k < ArrOdd.Count; k++)
                {
                    dt.Rows.Add();
                    dt.Rows[k]["OddRecord"] = ArrOdd[k].ToString();
                }
                for (int L = 0; L < ArrEven.Count; L++)
                {
                    dt.Rows[L]["EvenRecord"] = ArrEven[L].ToString();
                }
                dgvEvenOddGridView.DataSource = dt;
                dgvEvenOddGridView.DataBind();
            }
        }
    }
}

Using arrayList to Bind SharePoint List Data

Using arrayList to Bind SharePoint List Data



Using arrayList to Bind SharePoint List Data.

Note:-
We can bind only two columns using Array List. If you want bind more than two columns again you have to use DataTable.
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="ArrGridViewUserControl.ascx.cs" Inherits="ArrGridView.ArrGridView.ArrGridViewUserControl" %>
<div>
<asp:GridView runat="server" ID="dgvBindArrayListData" AutoGenerateColumns="false" CellPadding="4"
    EnableModelValidation="True" ForeColor="#333333" GridLines="Both" Width="100%">
    <AlternatingRowStyle BackColor="White" />
    <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
    <Columns>
    <asp:BoundField HeaderText="Player Name" DataField="Text" />
    <asp:BoundField HeaderText="Location" DataField="Value" />
    </Columns>
</asp:GridView>
</div>
Ascx.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Security;
using System.Collections;
namespace ArrGridView.ArrGridView
{
    public partial class ArrGridViewUserControl : UserControl
    {
        ArrayList ArrItems = new ArrayList();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                dgvBindArrayListData.DataSource = getData();
                dgvBindArrayListData.DataBind();
            }
        }
        public ArrayList getData()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPWeb currentWeb = SPContext.Current.Web;
                SPList lst = currentWeb.Lists["Players Location"];
                SPListItemCollection myColl = lst.Items;
                if (myColl.Count > 0)
                {
                    int i = 0;
                    foreach (SPListItem item in myColl)
                    {
                       ArrItems.Add(new ListItem(item.Title.ToString(),item["Location"].ToString()));
                    }
                }
            });
            return ArrItems;
        }
    }
}

Wednesday, January 16, 2013

DateTimeControl in SharePoint 2010

SharePoint also offers a DateTime picker control that you can use in your web parts and application pages. This control has the name DateTimeControl and is located in the Microsoft.SharePoint.WebControls namespace of the Microsoft.SharePoint.dll. The date picker control looks like the following:
DateTimeControl
The control consists of two parts: the date part and the time part. Click the calendar icon if you want to pick a date.
DateTimeControl pick date
You can place it on your application page as follows:
<spuc:DateTimeControl runat="server" ID="DateTimePickerControl1" />
After having added the required directive at the top of the page:
<%@ Register TagPrefix="spuc" Namespace="Microsoft.SharePoint.WebControls"
             Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
The most important properties are:
  • SelectedDate: this gives you the date that has been set by the user. You can also set this property in code.
  • ErrorMessage: you can customize the error message by setting this property.
  • MaxDate: you can specify a maximum date, f.e. if a date cannot be set in the future like a birthdate.
  • MinDate: you can specify a minimum date, f.e if a date cannot be set in the past.
  • AutoPostPack: you can set this property to true if you want the control to react on a user selection. In that case you have to trigger the DateChanged event.
  • IsRequiredField: you can specify if the user must choose a date or if its optional.
You can also set properties to influence the rendering of the control:
  • DateOnly: When set to true, you will only see the date part.
  • TimeOnly: When set to true, you will only see a time part.
  • Calendar: this property is of the SPCalendarType and can be used to change the type of calendar
             DateTimeControl change calendar
  • FirstDayOfWeek: this is an integer value in the range 0 to 6 that indicates the first day of the week displayed in the DatePicker; where 0 indicates Sunday, 1 indicates Monday, and so on. The default is 0 (Sunday). Here in Europe we consider Monday as first day of the week (as a free Sunday is a remuneration for the hard work during the week :) .
  • FirstWeekOfYear: this is an integer value that indicates the first week of the year displayed in the DatePicker. Allowed values are: 0 (the week in which January 1 occurs), 1 (the first week that has at least four days in the new year), or 2 (the first full week of the year). The default is 0 (the week in which January 1 occurs).
  • HijriAdjurstment: Sets or retrieves the number of days to add or subtract from the calendar to accommodate the variances in the start and the end of Ramadan and to accommodate the date difference between countries/regions.
  • HoursMode24: here you can specify if you want the AM/PM notation, which is the default, or the 24 hour notation like in the image
              DateTimeControl hours24mode
  • LocaleID: sets or retrieves the control’s locale identifier.
  • ShowWeekNumber: if this property is set to true, the week number is rendered in the DatePicker at the beginning of each week.
              DateTimeControl showweeknumber
  • TimeZoneID: you can set this property if you need to show the time in another time zone.
  • UseTimeZoneAdjustment: sets or retrieves a value that indicates whether the time values in the control are automatically adjusted for daylight savings time.
  • WorkWeek: Sets or retrieves a seven-character string that indicates the work days in a week. (I tested it but it didn’t change a thing in the DatePicker).
More exotic properties are:
  • DatePickerJavascriptUrl: you can make the control execute your own javascript control by setting this property with the URL where your javascript is located ( f.e. http://litwareinc.com/_layouts/myDatePicker.js).
  • DatePickerFrameUrl
  • OnValueChangeClientScript
If you want to use the date picker control in a web part you have to add the control in code.
DateTimeControl datetimepicker;
protected override void CreateChildControls()
{
        base.CreateChildControls();
        datetimepicker= new DateTimeControl();
        datetimepicker.ID = "datetimeControl1";
        this.Controls.Add(datetimepicker);
 
        // initialize other controls
}
If in your code you want to test if the user selected a date in the DateTimeControl, you have to use the IsDateEmpty property instead of the SelectedDate. If the user didn’t enter a date, the SelectedDate property will return today’s date.

protected void Submit()
{
      Customer newCustomer = new Customer();
      newCustomer.Name = "Company A";
      if (!datetimepicker.IsDateEmpty)
      {
          newCustomer.StartDate = datetimepicker.SelectedDate;
      }
}

Date and Time Field in SharePoint 2010 Programmatically Using VS 2010

Introduction

Today, in this article let's play around with one of the interesting and most useful concepts in SharePoint 2010.

Question: What is a list?

In simple terms "When you create a custom list, a new empty list is created with just two columns - Title and Attachments. The list contains a single default view. Once you create the list, you can add more columns, views, and so on".

I think we are now good to go and implement this wonderful concept.

Step 1: Create a custom list and modify the view.

Step 2: Open SharePoint 2010 Central Administration and navigate to a specific site.

Step 3: Open up Visual Studio 2010 and create an "Empty SharePoint project".

datetime1.gif

Step 4: Select "Deploy as a farm solution" and click on the "Finish" button. Now an empty project will be created:

datetime2.gif

Step 5: Add a new visual webpart for that project.

datetime3.gif

Step 6: The complete code of visualwebpart1usercontrol.ascx looks like this:
<%@ 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="DateandTimeUserControl.ascx.cs"Inherits="DateandTimeList.DateandTime.DateandTimeUserControl"%><div style="text-align: center;">        <table>            <tr>                <td colspan="2">                    <asp:Label ID="Label9" runat="server" Text="List Choice via Object Modelling - SharePoint 2010"                        Font-Bold="true" Font-Size="Large" Font-Names="Verdana" ForeColor="Maroon"></asp:Label>                </td>            </tr>            <tr>                <td>                    <asp:Label ID="Label10" runat="server" Text="Please Enter First Column Name" Font-Size="Large"                        Font-Names="Verdana" Font-Italic="true"></asp:Label>                </td>                <td>                    <asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>                </td>            </tr>            <tr>                <td>                    <asp:Label ID="Label11" runat="server" Text="Please Enter Second Column Name" Font-Size="Large"                        Font-Names="Verdana" Font-Italic="true"></asp:Label>                </td>
                <td>                    <asp:TextBox ID="TextBox8" runat="server"></asp:TextBox>                </td>            </tr>            <tr>                <td>                    <asp:Label ID="Label12" runat="server" Text="Please Enter Third Choice Column Name"                        Font-Size="Large" Font-Names="Verdana" Font-Italic="true"></asp:Label>                </td>                <td>                    <asp:TextBox ID="TextBox9" runat="server"></asp:TextBox>                </td>            </tr>            <tr>                <td>                    <asp:Label ID="Label13" runat="server" Text="Please Enter Fourth Date & Time Column Name"                        Font-Size="Large" Font-Names="Verdana" Font-Italic="true"></asp:Label>                </td>                <td>                    <asp:TextBox ID="TextBox10" runat="server"></asp:TextBox>                </td>            </tr>            <tr>                <td colspan="2">                    <br />                    <br />                    <fieldset>                        <legend style="font-family: Verdana; font-weight: bold; font-style: italic">Enter ChoiceList
                            Items</legend
>                        <br />                        <div style="text-align: center;">                            <table>                                <tr>                                    <td>                                        <asp:Label ID="Label14" runat="server" Text="Please Enter First List Item Name "                                            Font-Size="Large" Font-Names="Verdana" Font-Italic="true"></asp:Label>                                    </td>                                    <td style="text-align: right">                                        <asp:TextBox ID="TextBox11" runat="server"></asp:TextBox>                                    </td>                                </tr>                                <tr>                                    <td>                                        <asp:Label ID="Label15" runat="server" Text="Please Enter Second List Item Name "                                            Font-Size="Large" Font-Names="Verdana" Font-Italic="true"></asp:Label>                                    </td>                                    <td style="text-align: right">                                        <asp:TextBox ID="TextBox12" runat="server"></asp:TextBox>                                    </td>                                </tr>                            </table>                            <br />                            <br />                        </div>                    </fieldset>                </td>            </tr>            <tr>                <td colspan="2">                    <asp:Button ID="Button1" runat="server" Text="Create List Fields" Font-Names="Verdana"                        Width="166px" BackColor="Orange" Font-Bold="True" OnClick="Button2_Click" />                </td>            </tr>            <tr>                <td colspan="2">                    <asp:Label ID="Label16" runat="server" Font-Bold="true" Font-Names="Verdana" ForeColor="Maroon"></asp:Label>                </td>            </tr>        </table>    </div>

Step 7: The complete code of visualwebpart1usercontrol.ascx.cs looks like this:
using System;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using Microsoft.SharePoint;using WebApplication1; 
namespace
DateandTimeList.DateandTime
{
    public partial class DateandTimeUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            TextBox1.Focus();
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(TextBox1.Text) || string.IsNullOrEmpty
                (TextBox2.Text) || string.IsNullOrEmpty(TextBox3.Text) || string.IsNullOrEmpty
                (TextBox4.Text) || string.IsNullOrEmpty(TextBox5.Text) || string.IsNullOrEmpty
                (TextBox6.Text))
            {
                Label5.Text = "Please Enter Some Values";
                Label5.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                SPSite site = SPContext.Current.Site;
                SPWeb web = site.OpenWeb();
                web.AllowUnsafeUpdates = true;
                SPList list = web.Lists["Person"];
                SPListItem item = list.Items.Add();

                item.Fields.Add(TextBox1.Text, SPFieldType.Text, true);
                item.Fields.Add(TextBox2.Text, SPFieldType.Text, true);

                SPFieldChoice fieldChoice = (SPFieldChoice)list.Fields.GetFieldByInternalName
                    (item.Fields.Add(TextBox3.Text, SPFieldType.Choice, true));

                string[] types = { TextBox4.Text, TextBox5.Text };
                fieldChoice.Choices.AddRange(types);
                fieldChoice.Update();

                SPFieldDateTime dateTime = new SPFieldDateTime(list.Fields, list.Fields.Add(
                    TextBox6.Text, SPFieldType.DateTime, true));

                dateTime.DisplayFormat = SPDateTimeFieldFormatType.DateTime;
                dateTime.Update();
                SPView view = list.DefaultView;
                view.ViewFields.Add(TextBox1.Text);
                view.ViewFields.Add(TextBox2.Text);
                view.ViewFields.Add(TextBox3.Text);
                view.ViewFields.Add(TextBox6.Text);
                view.Update();

                Label5.Text = "Fields Created Successfully";
                Label5.ForeColor = System.Drawing.Color.Green;
                TextBox1.Text = string.Empty;
                TextBox2.Text = string.Empty;
                TextBox3.Text = string.Empty;
                TextBox4.Text = string.Empty;
                TextBox5.Text = string.Empty;
                TextBox6.Text = string.Empty;
            }
        }
    }
}

Step 8: Deploy the solution file and add the created webpart to a SharePoint site.

Step 9: The output of the application looks like this:

Output4.png

Step 10: By entering a DateTime field, the output of the application looks like this:

Output5.png

Step 11: When entering data in the list output of the application, it looks like this:

Output6.png

Step 12: When data is entered in the list output of the application, it looks like this:

Output7.png