In this article I am going to explain how you can access data in your BCS data source, by utilizing the Client Object Model.
- Go to Visual Studio 2010.
- Go to File New Project.
- Select Windows Application and apply the following settings to your project:
Target Framework: .NET 3.5
Build output: AnyCpu (or x64) - Click Add.
Next, we need to add references to the Client Object Model in order to be able to work with the client-side APIs from our Windows Application.
Right click the “References” node and choose “Add Reference”
· Choose Browse:
· Go to the following location:C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI.
· Select these two files:
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll
Add the following controls in your Windows Application Form:
· A new DataGridView control
· A new Button control
After adding controls you have to write the following code to access external list data:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SP1 = Microsoft.SharePoint;
using SP = Microsoft.SharePoint.Client;
namespace AccessExternalListData
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Define the Client Context (as defined in your textbox)
SP.ClientContext context = new SP.ClientContext("http://rohit:34143/");
SP.Web site = context.Web;
var StudentList = site.Lists.GetByTitle("StudentList");
SP.CamlQuery camlQuery = new SP.CamlQuery();
IQueryable<SP.ListItem> students =
StudentList.GetItems(camlQuery); StudentList.GetItems(camlQuery);
IEnumerable<SP.ListItem> externalList = context.LoadQuery(students);
context.ExecuteQuery();
var studentListData = from student in externalList
select new
{
// We're never pointing to the field at the 0-index
// because it's used by the BDC Identity itself. Hence our elements
start at 1. start at 1.
StudentID = student.FieldValues.ElementAt(1).Value.ToString(),
StudentName = student.FieldValues.ElementAt(2).Value.ToString(),
StudentCourse = student.FieldValues.ElementAt(3).Value.ToString()
};
// Simply clear the rows and columns of the GridView
gvStudents.Rows.Clear();
gvStudents.Columns.Clear();
// Add the columns we need (ProductID, Name, Description)
gvStudents.Columns.Add("StudentID", "StudentID");
gvStudents.Columns.Add("Name", "Name");
gvStudents.Columns.Add("Course", "Course");
foreach (var stud in studentListData)
{
// For each product in the list, add a new row to the GridView
gvStudents.Rows.Add(stud.StudentID, stud.StudentName, stud.StudentCourse);
}
}
}
}
Thanks for reading this article. I think this will help you a lot.
Leave Comment