Bind SharePoint List Items in a Gridview

Open the team site.

team site

Create a sample list “Employee”.

Open the team site

Add some values into the list.

Employee

Open Visual Studio then create a new Visual Webpart.



Enter a valid site URL then select Deploy as a Farm solution.

new visual webpart

Create a new Visual Webpart in the project.

Select Deploy as a farm solution

Now open EmployeeRegistration.ascx.

Create a GridView.

Create a new visual webpart

Code

  1. <asp:GridView ID="mygrid" runat="server" AutoGenerateColumns="false">  
  2.     <Columns>  
  3.         <asp:BoundField DataField="Name" HeaderText="  
  4.             Name" />  
  5.          <asp:BoundField DataField="Email" HeaderText="Email" />  
  6.           
  7.            
  8.     </Columns>  
  9. </asp:GridView>  
Create a GridView

Now open EmployeeRegistration.ascx.cs.

Code
  1. using System;  
  2. using System.ComponentModel;  
  3. using System.Web.UI.WebControls.WebParts;  
  4. using Microsoft.SharePoint;  
  5. using System.Data;  
  6.   
  7. namespace BindListData.EmployeeRegistration  
  8. {  
  9.     [ToolboxItemAttribute(false)]  
  10.     public partial class EmployeeRegistration : WebPart  
  11.     {  
  12.         // Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution  
  13.         // using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready  
  14.         // for production. Because the SecurityPermission attribute bypasses the security check for callers of  
  15.         // your constructor, it's not recommended for production purposes.  
  16.         // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]  
  17.         public EmployeeRegistration()  
  18.         {  
  19.         }  
  20.   
  21.         protected override void OnInit(EventArgs e)  
  22.         {  
  23.             base.OnInit(e);  
  24.             InitializeControl();  
  25.         }  
  26.   
  27.         protected void Page_Load(object sender, EventArgs e)  
  28.         {  
  29.             SPWeb web = SPContext.Current.Web;  
  30.             SPList list = web.Lists["Employee"];  
  31.             SPListItemCollection items = list.Items;  
  32.             mygrid.DataSource = items.GetDataTable();  
  33.             mygrid.DataBind();  
  34.   
  35.   
  36.         }  
  37.     }  
  38. }  
Now deploy the webpart.

Deploy

Now the result.

result

output

Happy SharePointing!

Regards: Vinodh.N (SharePoint developer / administrator).