Sunday, May 17, 2015

Editing SharePoint List with Server Object Model

I am having a list called Employees which I have to edit using Visual Web Part.


private SPListItemCollection GetEmployee()
{
    SPSite site = new SPSite("http://toshiba-pc");
    SPWeb web = site.RootWeb;

    SPList lis = web.Lists["Employee"];
    SPQuery q = new SPQuery();
    q.Query = String.Format("<Where><Contains><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Contains></Where>", txtEmployee.Text);

    q.ViewFields = "<FieldRef Name='Employee_x0020_Location'/><FieldRef Name='Years_x0020_Of_x0020_Experience'/>";
     SPListItemCollection lic = lis.GetItems(q);
     return lic;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
      SPListItemCollection lic = GetEmployee();
      SPListItem li = lic[0];
      txtLocation.Text = li["Employee_x0020_Location"].ToString();
      int? intYears = Int32.Parse(li["Years_x0020_Of_x0020_Experience"].ToString());
      txtYearsOfExp.Text = intYears.ToString();
}

protected void btnEdit_Click(object sender, EventArgs e)
{
      SPListItemCollection lic = GetEmployee();
      SPListItem li = lic[0];
      li["Employee_x0020_Location"] = txtLocation.Text;
      li["Years_x0020_Of_x0020_Experience"] = txtYearsOfExp.Text;
      li.Update();
}


I am making use of CAML query to extract the details of the Employee and fill the details in the TextBox, which is later updated.


No comments:

Post a Comment