RSS

Monthly Archives: November 2012

Programatically select and bind Sharepoint list items to ASP.NET controls


  • Open Visual Studio 2010
  • Create New Project
  • Select your Sharepoint site
  • Create Visual Webpart
  • Add LAbels,Textboxes or Dropdownlist (NOTE: Update control names in your code accordingly)
  • Use below code in page load event

try
{

SPQuery query = new SPQuery();
query.Query = “”;
query.ViewFields = “”;
query.RowLimit = 100;

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{

using (SPWeb web = site.OpenWeb())
{

SPList list = web.Lists.TryGetList(“—ADD LIST NAME—“);

//Check List Exists

if (list != null)

{

//Check ITEMS Exists

if (list.GetItems(query).GetDataTable() != null)
{
DataTableReader rdr = list.GetItems(query).GetDataTable().CreateDataReader();

if (rdr.Read())

//Bind list items to ASP.NET Label

Label1.Text = rdr[“Test_x0020_Item1”].ToString();
Label2.Text = rdr[“TestField2”].ToString();

//To bind DROPDOWNLIST uncomment below code
// dropdownlist1.DataSource = rdr;
// dropdownlist1.DataTextField = “Title”;
// dropdownlist1.DataValueField = “Title”;
// dropdownlist1.DataBind();

//To bind REPEATER uncomment below code
// Repeater1.DataSource = rdr;
// Repeater1.DataBind();

rdr.Close();

}
else
{
lblInfo.Text = “No Items Found”;
}
}
else
{
lblErrorMessage.Text = “List not found.Please make sure list is created and go to webpart settings to add the List name “;
}
}

}
}

catch (Exception ex)
{
lblErrorMessage.Text = ex.Message.ToString();
}

 
 

Tags: ,

Programatically Insert Items to Sharepoint 2010 List using C#.net


  • Open Visual Studio 2010
  • Create New Project
  • Select Your Sharepoint site
  • Create New Visual Webpart
  • Add Textbox,Label and Button as required(NOTE: Controls names You need to update in below code)
  • Add below code in button click event the code

try
{

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{

SPList List = web.Lists.TryGetList(“—ADD LIST NAME—“);
if (List != null)
{

SPListItem NewItem = List.Items.Add();

{
web.AllowUnsafeUpdates = true;

NewItem[“Title”] = Label1.Text;
NewItem[“Employee Name”] = Label2.Text;
NewItem[“Comments”] = Textbox1.Text;

NewItem.Update();

//int newID = NewItem.ID;

web.AllowUnsafeUpdates = false;

lblInfo.Text = “Item Inserted Successfully.”;

}
}
}

}

}
else
{
lblErrorMessage.Text = “List not found. Configure the list from webpart settings”;
}
}

}
}

catch (Exception ex)
{
lblErrorMessage.Text = ex.Message.ToString();
}

 
2 Comments

Posted by on November 14, 2012 in Code Snippets, Uncategorized, Visual web part

 

Tags: , ,