Saturday, 5 July 2014

SharePoint 2010 DataList Control


1. Create ListA
2.Click on List Settings
3. Click on "Title"
4. Change "Title" name to "Subject"
5. Click ok
6. Add new items for ListA, ex: English, Maths,Computers

1. Create New list: ListB
2. Click on List Settings
3. Click on "Title"
4. Change "Title" name to "Period"
5. Add new column Subject, type should be look up column
6. Select ListA, and Column is Subject
7. OK
8. Add new items in Listb

Open VS 2010
Create new sharepoint empty solution
Name it: TimeTable
Select farm solution
Add new item, select Visual Web part. Name it: WPTimeTable
Open WPTimeTableUserControl.ascx
Add below code
<table>
<tr>
<td>
<table border="1">
<tr>
<td>
Monday
</td>
<td>
<asp:DataList ID="DataList1" runat="server" DataKeyField="Title" RepeatDirection="Horizontal"
CellPadding="3" CellSpacing="2" BorderStyle="Solid" BorderWidth="2px">
<HeaderStyle BackColor="#A55129" Font-Bold="True" Font-Size="Large" ForeColor="White"
HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<ItemTemplate>
<asp:Label ID="lblPeriod" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Title") %>'></asp:Label>
<hr />
<br />
<asp:Label ID="lblSubject" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Subject") %>'>
</asp:Label>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</table>
</td>
</tr>
</table>
Open .cs file
Add below code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

SPList list = SPContext.Current.Web.Lists["Listb"];
SPQuery query = new SPQuery();
if (list != null)
{
DataTable dt = new DataTable();
dt = list.GetItems(query).GetDataTable();
DataList1.DataSource = dt;
DataList1.DataBind();
}
}
}
The final code for .cs is
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Data;

namespace TimeTable.WPTimeTable
{
public partial class WPTimeTableUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

SPList list = SPContext.Current.Web.Lists["Listb"];
SPQuery query = new SPQuery();
if (list != null)
{
DataTable dt = new DataTable();
dt = list.GetItems(query).GetDataTable();
DataList1.DataSource = dt;
DataList1.DataBind();
}
}
}
}
}

Deploy the solution
Insert webpart
You will get below out put
This is only for Monday, for next days we have to write code…
DataList in SHarePoint 2010