Showing posts with label List. Show all posts
Showing posts with label List. Show all posts

Saturday, June 30, 2012

Delete sharepoint list item attachment programmatically




Here is steps to delete sharepoint list item attachment programmatically.

- Follow the steps to delete list item attachment from your sharepoint list.

- Create new instance of site with your current application
using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
{

- Create new web instance and open web for current application
using (SPWeb web = site.OpenWeb())
{

- Create new list object and get your list
SPList SPLData = web.Lists["Your List Name"];

- Create new query object to hold query which fetches list item of the list
SPQuery SPMyQuery = new SPQuery();

- Assign query with value to it in ID field of the list item

SPMyQuery.Query = string.Format(“<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>{0}</Value></Eq></Where>”,1);

//========== Fetch item collection data for Your List  ==========//
SPListItemCollection common = SPLData.GetItems(SPMyQuery);

SPListItem listItem = common[0];

if (listItem.Attachments.Count > 0)
{
listItem.Attachments.Delete(“Name of file”);
listItem.Update();
}

}

}

-That’s it for deleting attachments from your existing list item of sharepoint list.

Wednesday, June 13, 2012

Get sharepoint list item attachment programmatically


Here is steps to get sharepoint list item attachment programmatically.

- Follow the steps to insert new item into your sharepoint list.

- Create new instance of site with your current application
using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
{

- Create new web instance and open web for current application
using (SPWeb web = site.OpenWeb())
{

- Create new list object and get your list
SPList SPLData = web.Lists["Your List Name"];

- Create new query object to hold query which fetches list item of the list
SPQuery SPMyQuery = new SPQuery();

- Assign query with value to it in ID field of the list item
SPMyQuery.Query = string.Format(“<Where
>  < Eq >  < FieldRef Name='ID' / >  < Value Type='Counter' > {0} < /Value >  < /Eq >  < /Where >”,1);

- Assign query to list and get item on the basis of the query build above
SPListItemCollection common = SPLData.GetItems(SPMyQuery);

- Check whether list collection contains result of the query, if contains item the proceed to update value of the list item
if (common.Count > 0)
{

SPListItem mylistItem = common[0];
string[] _Str_Attachments = GetAttachmentCollection(mylistItem);

- You can assign attachment collection with grid and if you want to give link to the attachment filename, on each file name with anchor link put following code for href of anchor.
string.Format("/Lists/{0}/Attachments/{1}/{2}", "Your List Name”,1,”FileName”);

}
}
}

- Get sharepoint list item attachment collection
public string[] GetAttachmentCollection(SPListItem item)
{
string FileNames = String.Empty;
if (item.Attachments.Count > 0)
{
string[] _Str_File_Name = new string[item.Attachments.Count];
for (int i = 0; i < item.Attachments.Count; i++)
{
SPFile file = item.ParentList.ParentWeb.GetFile(item.Attachments.UrlPrefix + item.Attachments[i].ToString());
_Str_File_Name[i]= file.Name;
}
return _Str_File_Name;
}
return null;
}



-That’s it for fetching attachments for existing item of sharepoint list.

Saturday, June 2, 2012

Insert new item with attachment to sharepoint list programmatically


Here is steps to add new item with attachment to sharepoint list programmatically.

- Get name of the file
string _Str_File_Name = fuAttachment.PostedFile.FileName;

- Get stream data by following way
byte[] contents = GetFileStream();

- Declare variable which hold the newly created item id.
int _Int_ID = 0;

- Follow the steps to insert new item into your sharepoint list with attachment.

- Create new instance of site with your current application
using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
{

- Create new web instance and open web for current application
using (SPWeb web = site.OpenWeb())
{

- Create new list object and get your list
SPList list = web.Lists["Your List Name"];

- Set allowunsafeupdates for web & site to true
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;

- Create new list item object and add new item for newly created list object
SPListItem item = list.Items.Add();

- Assign value for newly created item
item["Title"] = "Title1";

- Assign selected filename and stream data
if (!string.IsNullOrEmpty(_Str_File_Name != null) && (contents.Length > 0))
{
SPAttachmentCollection fileAttach = item.Attachments;
fileAttach.Add(_Str_File_Name, contents );
}


- Update item which will add new item to list
item.Update();

- if you want to manipulate on newly created item then you can get id of the newly created item by following way
itemId = item.ID;
}
}

- Convert your selected file to byte by following function
private byte[] GetFileStream()
{
//fuAttachment is your file select control
if (!fuAttachment.HasFile)
return null;
Stream fStream = fuAttachment.PostedFile.InputStream;
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
return contents;
}
Click Insert new item to sharepoint list programmatically to view my previous post to add item to sharepoint list.

-That’s it for adding new item to your sharepoint list with attachment.

Thursday, May 31, 2012

Delete sharepoint list item programmatically

- Create new instance of site with your current application
using (SPSite site = new SPSite(SPContext.Current.Web.ToString())) 
{

- Create new web instance and open web for current application
using (SPWeb web = site.OpenWeb())
{
- Create new list object and get your list
SPList SPLData = web.Lists["Your List Name"];

- Create new query object to hold query which fetches list item of the list
SPQuery SPMyQuery = new SPQuery();

- Assign query with value to it in ID field of the list item
SPMyQuery.Query = string.Format(“<Where><Eq><FieldRef Name='ID' /><Value Type='Counter' >{0}</Value> </Eq> </Where>”,1);

- Assign query to list and get item on the basis of the query build above
SPListItemCollection common = SPLData.GetItems(SPMyQuery);

- Check whether list collection contains result of the query, if contains item the proceed to update value of the list item
if (common.Count > 0)
{

- Set allowunsafeupdates for web to true
web.AllowUnsafeUpdates = true;

- Delete selected item from fetched list
common[0].Delete();

- Update item which will add new item to list
web.Update();

}
}


Tuesday, May 29, 2012

Update existing sharepoint list item programmatically


Here is steps to update existing sharepoint list item programmatically.

- Follow the steps to insert new item into your sharepoint list.

- Create new instance of site with your current application
using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
{

- Create new web instance and open web for current application
using (SPWeb web = site.OpenWeb())
{

- Create new list object and get your list
SPList SPLData = web.Lists["Your List Name"];

- Create new query object to hold query which fetches list item of the list
SPQuery SPMyQuery = new SPQuery();

- Assign query with value to it in ID field of the list item
SPMyQuery.Query = string.Format(“
< Where >  < Eq >  < FieldRef Name='ID' / >  < Value Type='Counter' > {0} < /Value >  < /Eq >  < /Where > ”,1); 

- Assign query to list and get item on the basis of the query build above
SPListItemCollection common = SPLData.GetItems(SPMyQuery);

- Check whether list collection contains result of the query, if contains item the proceed to update value of the list item
if (common.Count > 0)
{

- Set allowunsafeupdates for web to true
web.AllowUnsafeUpdates = true;


- Get first list item from the result list
SPListItem item = common[0];

- Set new value for the column which we want to update
item["Title"] = “New Value”;

- Update item which will add new item to list
item.Update();
}
}
}

-That’s it for updating existing item of sharepoint list.

Monday, May 28, 2012

Insert new item to sharepoint list programmatically


Here is steps to add new item to sharepoint list programmatically.
- Declare variable which hold the newly created item id.
int _Int_ID = 0;

- Follow the steps to insert new item into your sharepoint list.


- Create new instance of site with your current application
using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
{

- Create new web instance and open web for current application
        using (SPWeb web = site.OpenWeb())
        {

- Create new list object and get your list
                SPList list = web.Lists["Your List Name"];

- Set allowunsafeupdates for web & site to true
                site.AllowUnsafeUpdates = true;
                web.AllowUnsafeUpdates = true;

- Create new list item object and add new item for newly created list object
                SPListItem item = list.Items.Add();
- Assign value for newly created item
                item["Title"] = "Title1";
- Update item which will add new item to list
                item.Update();
- if you want to manipulate on newly created item then you can get id of the newly created item by following way
                itemId = item.ID;
        }
}

-That’s it for adding new item to your sharepoint list.

Thursday, May 17, 2012

How to Create New Sharepoint List Programmatically

Creation of new list includes following things.
- Create new list
- Create new field to newly created list
- Create new field which will set default value when new item created
- Show newly created field in view list of list
- Create lookup column to newly created list
- If list is already exist then create column to it


Here is the steps to create product list and columns in it.
(1) First, get list with name “Product” and check whether list is not null.

SPList ListProduct = web.Lists.TryGetList(“Product”);
if (ListProduct == null)
{

(2) if “Product” list is null then following step will create new list for sharepoint
web.Lists.Add(“Product”, "Product List Instance", SPListTemplateType.GenericList);
web.Update();

(3) After Creation of list “Product”, again, Get newly create list “Product”
SPList ProductList = web.Lists[“Product”];

(4) if you want to set product list to be appear on quick launch bar of sharepoint site then make it true/false accordingly
ProductList.OnQuickLaunch = false;

(5) Create field with name “Active”, if you want to add default value for field this way you can add default value

SPFieldBoolean fldActive = (SPFieldBoolean)ProductList.Fields.CreateNewField(SPFieldType.Boolean.ToString(), "Active");
fldActive.DefaultValue = "1";
ProductList.Fields.Add(fldActive);

(6) Simply, if you want to add field and there is no need to put any default value on the time of creation of new item you can add field by following way.
ProductList.Fields.Add("Description", SPFieldType.Note, false);

(7) After adding fields to List, update list.
ProductList.Update();

(8) After creation of list, then adding new fields to list, if you want to add newly added fields to view list of list then call following function.
CommonMethods.SetFieldInViewField(ProductList, "Active");

CommonMethods.SetFieldInViewField(ProductList, "Description");
(9) from above code we have added those column which are simple to add, but if you want to add any lookup column to list then use following step.
- Get list which you want to use as reference to lookup column
SPList ListCategory = web.Lists.TryGetList(“Category”);

- Call following function which will add new column named “Category” to “Product” list and adds reference of list “Category” with its field “Title”
CommonMethods.CreateLookupColumn(ProductList , ListCategory, "Category", "Title");

(10) Again, after creation of field, just put “Category” field to view list of list

//========== put field in view fields ==========//
CommonMethods.SetFieldInViewField(ProductList , "Category");
}

- To Set field in view list of list, use following function
public static void SetFieldInViewField(SPList ListName, string _Str_Column_Name)
{
SPView oView = ListName.Views["All Items"];
SPViewFieldCollection collViewFields = oView.ViewFields;
collViewFields.Add(_Str_Column_Name);
oView.Update();
}

- To add lookup column, use following function
public static void CreateLookupColumn(SPList Lst_Source_List, SPList Lst_Lookup_List, string _Str_Target_Column_Name, string _Str_Lookup_Column_Name)
{
SPList ListTest = Lst_Source_List;
ListTest.Fields.AddLookup(_Str_Target_Column_Name, Lst_Lookup_List.ID, false);
SPFieldLookup lkp = (SPFieldLookup)ListTest.Fields[_Str_Target_Column_Name];
lkp.LookupField = Lst_Lookup_List.Fields[_Str_Lookup_Column_Name].InternalName;
lkp.Update();
}

- To create new column when list is exist follow steps given below.
(1) SPList ListProduct = web.Lists.TryGetList(“Product”);
(2) if(ListProduct != null)
{
- Check whether the column with name “SortOrder” is not exist then add new column
if (!ListProduct .Fields.ContainsFieldWithStaticName("SortOrder"))
{
- Add new column and update list
ListProduct .Fields.Add("SortOrder", SPFieldType.Number, false);
ListProduct .Update();
- Add newly created column to view list of the list

//========== put field in view fields ==========//
CommonMethods.SetFieldInViewField(ListProduct , "SortOrder");
}
}

so, that’s it for all.