27 Sep

Add a New Item to a List

So we just talked about how to display data in a visual web part, now let’s talk about making customized forms for the user to enter data into a list.


Sample Data

First, I created an empty list in honor of my caffeine addiction.

 
AddItem01
 

In addition to the Title column, this list has some extra columns with different data types.
 

AddItem04 

Our task is to make a simple un-styled form with controls that correspond to the columns.
 

AddItem02 

Once the user clicks the button, the item gets added to the list.

 
AddItem03


Preliminary Steps

1. Create a new SharePoint 2010 Project (Visual C#) in Visual Studio 2010, or use an existing one.

2. Add a Visual Web Part to the project.

3. Open up the UserControl (the .ascx file) and add the appropriate form controls (text boxes, drop down choices, checkboxes, etc.) that correspond to the columns in the list.

4. Add a button control with an OnClick attribute and function name.

5. Open the .ascx.cs file (F7).


Add a New Item to the List

1. Create a method for the OnClick event. Be sure to place it inside the class brackets.

2. Select the list. First select the site, then indicate which list with SPList. Alternatively, you can use SPListItemCollection, select the Items, and adjust the following steps accordingly.

3. Add a new (empty) List Item to the list. If you’re using SPList, use the AddItem() method; if using SPListItemCollection, then use Add().

4. Set the values for each of the columns. Assign to each column in that item to the data from each corresponding form control.

5. Finally, call the Update() method to the item. Don’t forget this step!

6. Optionally, you can clear the text boxes, or send the user to the list view. Or you could display a success message, but just give the user some indication that the action succeeded.


Final Steps

  1. Package and deploy the project.
  2. If necessary, navigate to the site collection and activate the feature with the visual web part.
  3. Create a new web part page or edit an existing one. When you click insert a web part, the visual web part is under the Custom category.
  4. Add the visual web part to the page and save.

 

Copyright © 2014 Keren Apura; Fruitful theme by fruitfulcode