Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add a New Item to a SharePoint List
<!-- Assemblies, imports, and registrations go here -->
<table>
<tr>
<td>Drink Name:</td>
<td>
<asp:TextBox ID="TitleTextBox" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Size:</td>
<td>
<asp:DropDownList ID="SizeDropDownList" runat="server">
<asp:ListItem Text="Tall" Value="Tall" Selected="True" />
<asp:ListItem Text="Grande" Value="Grande" />
<asp:ListItem Text="Venti" Value="Venti" />
</asp:DropDownList>
</td>
</tr>
<tr>
<td>Calories:</td>
<td>
<asp:TextBox ID="CaloriesTextBox" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Seasonal?</td>
<td>
<asp:CheckBox ID="SeasonalCheckBox" runat="server" />
</td>
</tr>
<tr>
<td colspan="2"><asp:Button ID="SaveButton" runat="server" Text="Add" OnClick="Add_New" /></td>
</tr>
</table>
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
namespace SampleProject.AddNewItem
{
public partial class AddNewItemUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
} //end Page_Load
protected void Add_New(object sender, EventArgs e)
{
//Select the list
SPWeb thisWeb = SPContext.Current.Web;
SPList sampleList = thisWeb.Lists["Starbucks"];
//Add a new item to the list
SPListItem item = sampleList.AddItem();
//Store values entered into the textbox
item["Title"] = TitleTextBox.Text;
item["Size"] = SizeDropDownList.SelectedValue;
item["Calories"] = Convert.ToInt32(CaloriesTextBox.Text);
item["Seasonal"] = SeasonalCheckBox.Checked;
//Finally, save
item.Update();
//Go to the list view
Response.Redirect("http://localhost/sample/Lists/Starbucks/AllItems.aspx");
} //end Add_New
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.