|
using System; |
|
using System.Web.UI; |
|
using System.Web.UI.WebControls; |
|
using System.Web.UI.WebControls.WebParts; |
|
using System.Data; |
|
using Microsoft.SharePoint; |
|
|
|
namespace SampleProject.DisplayGridView |
|
{ |
|
public partial class DisplayGridViewUserControl : UserControl |
|
{ |
|
protected void Page_Load(object sender, EventArgs e) |
|
{ |
|
if (!IsPostBack) |
|
{ |
|
//Select the current site, assuming the list is in this site. |
|
SPWeb thisWeb = SPContext.Current.Web; |
|
|
|
//Simple query on a Custom List with a column named Filter (Yes/No). |
|
SPQuery queryList = new SPQuery(); |
|
queryList.ViewFields = "<FieldRef Name='ID' />" |
|
+ "<FieldRef Name='Title' />"; |
|
queryList.Query = "<Where><Eq>" |
|
+ "<FieldRef Name='Filter' />" |
|
+ "<Value Type='Integer'>1</Value>" |
|
+ "</Eq></Where>"; |
|
queryList.ViewFieldsOnly = true; |
|
|
|
//The list name is Sample List. |
|
SPList thisList = thisWeb.Lists["Sample List"]; |
|
SPListItemCollection queryResults = thisList.GetItems(queryList); |
|
|
|
//Two columns. I purposely named them differently than their names in the list |
|
//to prevent confusion & show the difference in this example. |
|
DataTable dt = new DataTable(); |
|
dt.Columns.Add("Item ID", typeof(int)); |
|
dt.Columns.Add("Item Title", typeof(string)); |
|
|
|
//Each item in the collection creates a row in the data table. |
|
if (queryResults.Count > 0) |
|
{ |
|
foreach (SPListItem item in queryResults) |
|
{ |
|
DataRow dr = dt.NewRow(); |
|
|
|
dr["Item ID"] = item["ID"]; |
|
dr["Item Title"] = item["Title"] != null ? item["Title"].ToString() : string.Empty; |
|
|
|
dt.Rows.Add(dr); |
|
} |
|
} |
|
else Label1.Text = "There are no items to display."; |
|
|
|
//ID- Notice that I’ve made the Header Text different from both the internal field name |
|
//and the data table column name. This is what will be displayed. |
|
BoundField bf = new BoundField(); |
|
bf.DataField = "Item ID"; |
|
bf.HeaderText = "ID #"; |
|
bf.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; |
|
bf.ItemStyle.HorizontalAlign = HorizontalAlign.Center; |
|
bf.ItemStyle.Width = Unit.Pixel(50); |
|
GridView1.Columns.Add(bf); |
|
//Title- the Header Text is now “Sample Items”. |
|
bf = new BoundField(); |
|
bf.DataField = "Item Title"; |
|
bf.HeaderText = "Sample Items"; |
|
bf.HeaderStyle.HorizontalAlign = HorizontalAlign.Left; |
|
bf.ItemStyle.HorizontalAlign = HorizontalAlign.Left; |
|
bf.ItemStyle.Width = Unit.Pixel(650); |
|
GridView1.Columns.Add(bf); |
|
|
|
//This is the last step, congratulations! |
|
GridView1.AutoGenerateColumns = false; |
|
GridView1.DataSource = dt; |
|
GridView1.DataBind(); |
|
} |
|
} |
|
} |
|
} |
Hi,
I am not able to view list items in grid view, I am getting blank page web part.
kindly help me on this.
Regards,
Selvan J