Skip to content

Instantly share code, notes, and snippets.

@devendrasv
Last active December 11, 2015 21:09
Show Gist options
  • Save devendrasv/4660401 to your computer and use it in GitHub Desktop.
Save devendrasv/4660401 to your computer and use it in GitHub Desktop.
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
namespace SharePoint_webpart.Projects
{
[ToolboxItemAttribute(false)]
public class Projects : WebPart
{
//declare all variables
TextBox txtproject;
Button btnadd;
GridView grdprojects;
// A table for layout
Table tbl;
TableRow row;
TableCell cell;
//load all controls
protected override void CreateChildControls()
{
tbl = new Table();
row = new TableRow();
cell = new TableCell();
txtproject = new TextBox();
txtproject.ID = "txtproject";
cell.Controls.Add(txtproject);
cell.Width = 10;
row.Controls.Add(cell);
btnadd = new Button();
btnadd.ID = "btnadd";
btnadd.Text = "Add Project";
btnadd.Click += btnadd_Click;
cell = new TableCell();
cell.Controls.Add(btnadd);
row.Controls.Add(cell);
tbl.Controls.Add(row);
row = new TableRow();
cell = new TableCell();
cell.ColumnSpan = 2;
grdprojects = new GridView();
grdprojects.AutoGenerateColumns = true;
grdprojects.DataSource = getdata();
grdprojects.DataBind();
cell.Controls.Add(grdprojects);
row.Controls.Add(cell);
tbl.Controls.Add(row);
Controls.Add(tbl);
}
private DataTable getdata()
{
SPWeb web = SPContext.Current.Web;
SPList projectsList = web.GetList("http://sharepoint-journey/sites/Apps/Lists/Projects/AllItems.aspx");
//In the below CAMl query i am using Where condition even though it is not applicable, so that you can always remebre the standard sysntax.
var query = "<Query>" +
"<Where>" +
"<Neq>" +
"<FieldRef Name='ID'/><Value Type='Number'>0</Value>" +
"</Neq>" +
"</Where>" +
"<OrderBy>" +
"<FieldRef Name='Title'/>" +
"</OrderBy>" +
"</Query>";
SPQuery spQuery = new SPQuery();
spQuery.ViewFields = "<FieldRef Name='Id' /><FieldRef Name='Title' />";
spQuery.Query = query;
SPListItemCollection items = projectsList.GetItems(spQuery);
DataTable dtprojects = items.GetDataTable();
return dtprojects;
}
//Add the project to a list
void btnadd_Click(object sender, EventArgs e)
{
SPWeb web = SPContext.Current.Web;
SPList projectsList = web.GetList("http://sharepoint-journey/sites/Apps/Lists/Projects/AllItems.aspx");
SPListItem newItem = projectsList.Items.Add();
newItem["Title"] = txtproject.Text.ToString();
newItem.Update();
txtproject.Text = string.Empty;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment