Saturday, October 8, 2011

How to add item to Sharepoint List

In this article I will show you how to add record to Sharepoint List using Sharepoint web part. The list name is ContactUs and following are the field to fill “Name”,” Email”, “WebSite”, “Telephone”, “Company”, “JobRole”,” Comment”, “How_do_you_hear “ and “UseSocialSite”



// following SPSecurity.RunWithElevatedPrivileges code will ignore the 
// security privilege check in the share point
SPSecurity.RunWithElevatedPrivileges(()=>
{
    // create spsite object from current url
    SPSite site = new SPSite(SPContext.Current.Web.Url);   
    // crate web oject using site
    SPWeb web = site.OpenWeb();
    // Get ContactUs
    SPList Contact = web.Lists["ContactUs"];
    SPQuery query = new SPQuery();

    SPListItemCollection ContactUs = Contact.GetItems(query);

    site.AllowUnsafeUpdates = true;
    web.AllowUnsafeUpdates = true;

    SPListItem NewContactUs = Contact.Items.Add();

    NewContactUs["Name"] = nameTextBox.Text;                      
    NewContactUs["Email"] = emailTextBox.Text;

    NewContactUs["WebSite"] = websiteTextBox.Text;
    NewContactUs["Telephone"] = telephoneTextBox.Text;
           
    NewContactUs["Company"] = websiteTextBox.Text;
    NewContactUs["JobRole"] = telephoneTextBox.Text;

    NewContactUs["Comment"] = commentTextBox.Text;
    NewContactUs["How_do_you_hear"] = howDropDownList.SelectedValue.ToString();
    NewContactUs["UseSocialSite"] = yesRadioButton.Checked?"Yes":"No";
    NewContactUs.Update();
    site.AllowUnsafeUpdates = false;
    web.AllowUnsafeUpdates = false;
            
    Page.Response.Redirect(SPContext.Current.Web.Url + "/Pages/ContactConfirm.aspx");
});

0 comments:

Post a Comment