Tuesday, March 27, 2012

Sharepoint List to gridview in sharepoint 2010

Here i will show how to access the the share point list data to Visual Web part in share point 2010 and the linq query is used to get the data from share point .Then Ive added the below code to web part user control.In can process the the list data to grid view
var Ldc = new SPLinqDataContext(SPContext.Current.Web.Url);
var Orderslist = Ldc.GetList("Orders");
var orederQueryResult = from order in orders where 
order.Dueate < DateTime.Now.AddMonths(6) select new { order.name, order.city, sname = order.name, DueDate =order.Date.Value.ToShortDateString() }; 
spGV.DataSource = orederQueryResult;
spGV.DataBind(); 
The above linq query gets order data based on orderdate
Using DataTable:
<asp:GridView ID="Gvdata" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" />
        <asp:BoundField DataField="Name" />
        <asp:BoundField DataField="DocumnetTYpe" />
        <asp:BoundField DataField="Role" />
        <asp:BoundField DataField="Key" />
    </Columns>
</asp:GridView>


using (SPSite s = new SPSite(url))
{
using (SPWeb sw = s.OpenWeb())
{
SPList sl = sw.Lists["Orders"];
DataTable ResTable = new DataTable();
ResTable.Columns.Add(new DataColumn("Id"));
ResTable.Columns.Add(new DataColumn("Name"));
ResTable.Columns.Add(new DataColumn("DocumentType"));
ResTable.Columns.Add(new DataColumn("Role"));
ResTable.Columns.Add(new DataColumn("Key"));
foreach (SPListItem item in sl.Items)
{
DataRow dr = ResTable.NewRow();
dr["Id"] = item.Id;
dr["Name"] = item.Name;
dr["DocumnetType"] = item.DocumnetType;
dr["Role"] = item.Role;
dr["Key"] = item.Key;
ResTable.Rows.Add(dr);
}
Gvdata.DataSource = ResTable;
Gvdata.DataBind();
}

No comments:

Bel