Custom Webpart – Inserts items into sharepoint custom list

10 October, 2008 (14:37) | MOSS - Object Model | By: GVK

Here is the simple custom webpart which inserts items into (Title, Employee Name, Designation) Sharepoint custom list, before executing the webpart first of all you have to create custom list and required fields manually through UI as said below:

Create a custom list, name it as Custom List (you can also choose different name, but make sure to modify the same in the code too) then create columns as mentioned…..

Title [Single line text] (this is by default available, no need of re-creating)

Employee Name [Single line text]

Designation [Single line text]

Insert Into Custom List - Input Form

Insert Into Custom List - Input Form

Download complete source code

Insert Into Custom List - Record Inserted

Insert Into Custom List - Record Inserted

List view displays records after inserting

List view displays records after inserting

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace InsertIntoList
{
    [Guid("4f70d2fa-e335-471d-94c6-5bec8d034032")]
    public class InsertIntoList : System.Web.UI.WebControls.WebParts.WebPart
    {
        TextBox oTextTitle;
        TextBox oTextName;
        TextBox oTextDesignation;
        Label oLabelMessage;
        Button oButtonSubmit;
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            oTextTitle = new TextBox();
            this.Controls.Add(oTextTitle);

            oTextName = new TextBox();
            this.Controls.Add(oTextName);

            oTextDesignation = new TextBox();
            this.Controls.Add(oTextDesignation);

            oLabelMessage = new Label();
            this.Controls.Add(oLabelMessage);

            oButtonSubmit = new Button();
            oButtonSubmit.Text = "Submit";
            oButtonSubmit.CssClass = "ms-ButtonHeightWidth";
            this.Controls.Add(oButtonSubmit);

            oButtonSubmit.Click += new EventHandler(oButtonSubmit_Click);
        }

        void oButtonSubmit_Click(object sender, EventArgs e)
        {
            if (oTextTitle.Text.Trim() == "" || oTextName.Text.Trim() == "" || oTextDesignation.Text.Trim() == "")
            {
                oLabelMessage.Text = "You must specify a value for this required field";
            }
            else
            {
                SPSite mySite = SPContext.Current.Site;
                SPWeb myWeb = SPContext.Current.Web;
                SPList myList = myWeb.Lists["Custom List"];
                SPListItem myListItem = myList.Items.Add();
                myListItem["Title"] = oTextTitle.Text.ToString();
                myListItem["Employee Name"] = oTextName.Text.ToString();
                myListItem["Designation"] = oTextDesignation.Text.ToString();
                myWeb.AllowUnsafeUpdates = true;
                myListItem.Update();
                myWeb.AllowUnsafeUpdates = false;
                oLabelMessage.Text = "Recorded inserted";
            }
        }

Comments

Comment from Rama kishore
Time June 12, 2009 at 6:51 am

Hi ,
I am able render the web part but i am unable to save the list data.

i am getting below error.

An unexpected error has occurred.

Web Parts Maintenance Page: If you have permission, you can use this page to temporarily close Web Parts or remove personal settings. For more information, contact your site administrator.
Troubleshoot issues with Windows SharePoint Services.

could u please tell me what is the reason behind this

Comment from Rama kishore
Time June 12, 2009 at 7:03 am

Hi,

can any one tell me how to use java script on submit button click event to validate fields and reset button on click event to clear text boxes

Comment from G Vijai Kumar
Time June 12, 2009 at 7:24 am

Ram, have you added the reference using System.Security; and attribute [assembly: AllowPartiallyTrustedCallers] on page AssemblyInfo.cs ?

Comment from Rama kishore
Time June 12, 2009 at 7:45 am

Hi GVK,
Thanks for your quick reply.
I have included system.security reference in my cs file,but i am to add [assembly: AllowPartiallyTrustedCallers] on page AssemblyInfo.cs

it showing below error
“The type or namespace name ‘AllowPartiallyTrustedCallers’ could not be found (are you missing a using directive or an assembly reference?) D:\DotNet Projects\Custom List\Custom List\Properties\AssemblyInfo.cs”

Comment from Rama kishore
Time June 12, 2009 at 7:46 am

sorry for the previous post
I have included system.security reference in my cs file,but i am unable to add [assembly: AllowPartiallyTrustedCallers] on page AssemblyInfo.cs

it showing below error
“The type or namespace name ‘AllowPartiallyTrustedCallers’ could not be found (are you missing a using directive or an assembly reference?) D:\DotNet Projects\Custom List\Custom List\Properties\AssemblyInfo.cs”

Comment from G Vijai Kumar
Time June 12, 2009 at 8:46 am

I guess you added the namespace System.Security on the wrong file, please it on AssemblyInfo.cs

you can see the format of AssemblyInfo.cs below:

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("IOTCustomSearchInputBox")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IOTCustomSearchInputBox")]
[assembly: AssemblyCopyright("Copyright © 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly:AllowPartiallyTrustedCallers]

Comment from Rama kishore
Time June 12, 2009 at 8:55 am

Yes i have included everything which you specified in ur post but still i am getting same error.may i know the reason behind it.

Comment from Rahul
Time August 25, 2009 at 10:51 am

Hi,
My task is something similar to you, I have an aspx page having one dropdown and one submit button. When i select a value(In Time) from dropdown & click on the submit button the value(In Time) gets store in sharepoint list & like this when i select another value(Out Time)
and click submit button Out time gets store in the sharepoint list. How can i do this.

Do I need to create aspx page in sharepoint designer or i need to create a custom web part?

Thank You

Comment from G Vijai Kumar
Time August 25, 2009 at 11:49 am

Rahul, you can directly create a custom webpart which inserts values into Sharepoint list same as above but with little modifications.

myitem["drop down column name"]=ddl.SelectedValue.ToString();

before the above line you have to populate the items in drop down list.

Comment from Gary
Time September 23, 2009 at 4:05 am

Thank you, this was a nice example to get up to speed quickly on lists. However, being very new to sharepoint dev it might help pointing out that people need to create the “Custom List” list and fields manually before following the example.

Thanks for the example.

Comment from G Vijai Kumar
Time September 23, 2009 at 5:38 am

Gary, thanks for your suggestions, added as you said on top of the post, thanks again :-)

Comment from Matty
Time October 2, 2009 at 1:13 pm

Hi, great web part, works really well – one thing though – could you show me the code that i would need to add a data entry (which contains todays date by default)

Thanks!

Comment from matt l
Time October 2, 2009 at 1:17 pm

Hi – great webpart. could you show me how i would add an extra input field for type “date” with (with the current date as default if poss)?

Cheers!
Matt

Comment from G Vijai Kumar
Time October 3, 2009 at 4:35 am

@ Matt: Add the below code lines as mentioned in commented lines, and make sure that ‘Date’ column is already existed in Sharepoint custom list before executing the code

// Declaration – Include the below lines on top of CreateChildControls() method
TextBox oTextDate; //Updates – Date input control
string cmonth = System.DateTime.Today.Month.ToString();//Updates – Current Month
string cday = System.DateTime.Today.Day.ToString();//Updates – Current Day
string cyear = System.DateTime.Today.Year.ToString();//Updates – Current Year
string cdate;//Updates – Current Date
cdate = cmonth + “/” + cday + “/” + cyear;//Concates all the above and to get Current Date in MM/DD/YYYY format

// Include the below lines in CreateChildControls() Method
oTextDate = new TextBox();//Updates
oTextDate.Text=cdate.ToString();//Updates
this.Controls.Add(oTextDate);//Updates

//Include the below line in Button Click Event
myListItem["Date"] = oTextDate.Text.ToString();//Updates – Inserts Date into custom list when button clicked

//Include the below lines in Render() method
oTextDate.RenderControl(writer);//Updates – Rendering the Date TextBox input control

Comment from matt l
Time November 16, 2009 at 2:14 pm

Thanks man, works a treat

Comment from Tom Davie
Time November 17, 2009 at 1:43 pm

Hi Rama,
I have been trying to build this web part, but when I try and import the web part into my SharePoint site, I see an error message “The “ContactForm” Web Part appears to be causing a problem. Object reference not set to an instance of an object.” I have included the Security reference and the AllowPartiallyTrustedCallers part of the assembly in the AssemblyInfo.cs Thanks

Comment from G Vijai Kumar
Time November 17, 2009 at 3:30 pm

@ Tom Davie: Could you please provide more information, have you got success in building the webpart or are you trying to deploy the solution directly from Visual Studio to Sharepoint, Also tell me about have to incorporated any additional code in your webpart other than what I have posted?

Comment from Tom Davie
Time November 17, 2009 at 3:51 pm

Hi,

I have used VS 2008 to build the webpart and it builds and deploys without error. I am only trying to test the webpart, it is not ready for production yet. The error occurs when I try to pick up the web part by selecting “Add a web part” as per your instructuions. The page then shows “Error ” with the error message I mentioned.The only additional code has been a few extra columns, but my sharepoint list has been changed accordingly to incorporate them.

Comment from Tom Davie
Time November 24, 2009 at 4:18 pm

Hi Vijai,

I got this working. Just hadn’t matched the fields correctly. Thanks for your code.
PS, sorry I got your name wrong.
TD

Comment from Rajender
Time November 26, 2009 at 6:06 am

Hi Vijai,
It is very good stuff, But how to add column names and controls (either text box or dropdown box without knowing the custom list control types)dynamically from custom list(with out assign names to labels directly/hard coding).. can u help in this

Comment from VG
Time November 26, 2009 at 9:29 am

Great Webpart..works well. Could u show me how i can dynamically add text box on selecting a particular check-box list item.

Comment from G Vijai Kumar
Time November 26, 2009 at 11:13 am

@VG: View this post http://www.fivenumber.com/sharepoint-list-form-generator/ for how to generate controls dynamically at run time.

Comment from venkat
Time December 10, 2009 at 8:37 am

It helped me alotttttttt……….Thank you very much.

Comment from Anand
Time December 14, 2009 at 11:38 am

its realy helpful for ,,,,,,,,,Thanks a lot

Comment from Prit
Time December 16, 2009 at 6:10 am

Hi,
Tooo Good Webpart…thankx a lot for this. I have added few drop down, checkboxes and radio buttons to this webpart. How to enable/disable the check boxes and radio button on selection of a particular item in the drop-down list. Thankx in advance.

Comment from sampathp
Time December 22, 2009 at 1:27 pm

im new to sharepoint .

I have one custome page attached to New Event of my Customlist and i have submit button on that custom page . when i click that submit button it should add the data to my custom list .
can any one help me?

Comment from G Vijai Kumar
Time December 22, 2009 at 2:47 pm

@Sampath P: I have shown the same in the current post, use the code and try to create a custom webpart, place the webpart in your custom page, you have to modify the below lines with you custom list name and appropriate column name
SPList myList = myWeb.Lists["Custom List"];//provide your list name
SPListItem myListItem = myList.Items.Add();
myListItem["Title"] = oTextTitle.Text.ToString();//your column names
myListItem["Employee Name"] = oTextName.Text.ToString();//your column names
myListItem["Designation"] = oTextDesignation.Text.ToString();//your column names

Comment from Rajender
Time December 26, 2009 at 2:50 pm

please help for —-dropdownlist save

Comment from Rajender
Time December 26, 2009 at 2:55 pm

i am using dropdownlist in Custom lists, how can i assign dropdown selected value– please help me

Comment from PJ
Time December 29, 2009 at 7:45 pm

Few questions

a) Can I use this code on a custom list that has been created using sharepoint UI where columns were added manually? (

b) Can I set the tabindex or position of each of the column as my list will have about 15 to 20 columns.

c) Is SPD only the option if I want to move some columns to another row (ie. merge along with another column)?

d) Can I handle javascrip here itself or do I need to stick to content-editor-webpart?

Thanks in advance.

Comment from G Vijai Kumar
Time December 30, 2009 at 4:45 am

@ PJ: a) Yes using the above code in the post you can insert items in to custom list that has been created using UI
b) Yes, you can set the tab index for the controls
c) No, you can use the code-behind to present the controls as you want
d) you can call javascript function in code-behind

Comment from Disha
Time February 7, 2010 at 3:45 pm

Hello Vijya

I want to create a customlist from third party sql database with the option of add/edit/delete record, so it will display list from third partry sql database and depending on add/edit/delete action, it will update directly third party sql database.

How can I do it

Comment from venkat
Time February 7, 2010 at 5:28 pm

Hi
can u tell me the usage of below command in above code

oButtonSubmit.CssClass = “ms-ButtonHeightWidth”;

Comment from G Vijai Kumar
Time February 8, 2010 at 6:45 am

@ Venkat: ‘CssClass’ is the property which apply’s the class ‘ms-ButtonHeightWidth’
I have used the CSS class to apply the same look and feel like Sharepoint webparts.
Sharepoint uses the same CSS class ‘ms-ButtonHeightWidth’ in New/Edit forms for OK, Cancel buttons

Comment from Venkat
Time February 8, 2010 at 8:22 am

Vijay,

Nice post!!!

How to filter the list values in the custom list and how to show in grid view .Pls advice us.

Eg.
title–employee name — desingation.

Comment from G Vijai Kumar
Time February 8, 2010 at 8:35 am

@ Venkat: Please follow the post on link (http://www.fivenumber.com/displaying-sharepoint-custom-list-items-in-spgridview/) to show the custom list items in Grid View

Comment from G Vijai Kumar
Time February 9, 2010 at 11:05 am

@ Disha: There are several ways to show SQL data into Sharepoint list and edit/update record, you can accomplish this using BDC, for more information please look into the links http://www.fivenumber.com/getting-started-with-business-data-catalog-in-sharepoint-2007/
http://www.lightningtools.com/bdc-meta-man/business-data-catalog-write-back.aspx
Another way: You can show the SQL data in a Grid View, then you can write back to SQL database (purely ASP.Net coding) but you should incorporate the Grid View in a custom webpart.

Comment from Hameem
Time March 25, 2010 at 4:35 am

Hi everybody,

iam new sharepoint server, i created one user login wepart in C#.net and also i imported into sharepoint site. this webpart contain two textbox and one button. my requirement is if i click the save button the two texbox value should save in the sharepoint custom list.how to write a code for this where to write?

thank you advance

Comment from mbh
Time August 31, 2010 at 10:03 am

Hi,
I have used ur code and I am able to render the web part correctly but it does not save data in the list. There is no error either. Can u please help.

Comment from G Vijai Kumar
Time September 1, 2010 at 1:19 pm

@ mbh: Have you tried to debug the code?

Comment from Dinesh
Time December 2, 2010 at 6:30 am

Thanks a lot sir. I got the correct output as mentioned in ur code.
Can u tell me how to take the custom list’s name dynamically as mentioned my site user?

Comment from Dinesh
Time December 2, 2010 at 7:09 am

Sir can u give me some example on how to take the values present in the gridview which is present in webpart into custom list.

Comment from Haneesh
Time December 3, 2010 at 1:56 pm

Hi,
I have used the above mentioned method to save data into a list in sharepoint it worked properly, but now i have requirement i.e. how can i save gridview data into a sharepoint custom list? Can any one suggest me please?

Thank you…

Comment from G Vijai Kumar
Time December 8, 2010 at 9:07 am

@ Dinesh: You can follow the link http://www.fivenumber.com/sharepoint-list-form-generator/ to set the list name dynamically, the link shows you how to populate the existing lists within the site, so that user can select the appropriate list and add the items into that particular list, let me know if you need more details, thanks for visiting the post, good luck :-)

Comment from Deny
Time July 20, 2011 at 4:31 am

I’ve tried your code, but when I input text to the fields always add colon when it was saved. for example: add “Mr” to Title saved “Mr,” to the list. All fields did the same. I have checked all code didn’t have any colon. And in my test, there was 2 textbox created for each field. 1 is for this.control.add(xxx) and the second one is for the render procedure.

can you help me?
thnx

Comment from Deny
Time July 20, 2011 at 5:49 am

solved it,
it because I didn’t delete the line: base.Render(writer);

thank you and sorry to bother u :)

Write a comment