Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Update SharePoint List Data in a GridView (Part 2)
<asp:GridView ID="StarbucksGridView" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="false"
OnRowEditing="Edit_Row" OnRowCancelingEdit="Cancel_Edit" OnRowDataBound="Row_Databound"
OnRowUpdating="Update_Row" CellPadding="4" EnableModelValidation="True"
ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="ID">
<EditItemTemplate>
<asp:Label ID="IDTextBox" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<EditItemTemplate>
<asp:TextBox ID="TitleTextBox" runat="server" Text='<%# Bind("Title") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Title") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Size">
<EditItemTemplate>
<asp:DropDownList ID="SizeDropDownList" runat="server">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Size") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Calories">
<EditItemTemplate>
<asp:TextBox ID="CaloriesTextBox" runat="server" Text='<%# Bind("Calories") %>' MaxLength="4"></asp:TextBox>
<asp:CompareValidator ID="CaloriesValidator" runat="server" ErrorMessage="*" ControlToValidate="CaloriesTextBox" Operator="DataTypeCheck" Type="Integer"></asp:CompareValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("Calories") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Seasonal">
<EditItemTemplate>
<asp:RadioButtonList ID="SeasonalRadioButtonList" runat="server">
<asp:ListItem Text="Yes" Value="true" />
<asp:ListItem Text="No" Value="false" />
</asp:RadioButtonList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="SeasonalLabel" runat="server" Text='<%# Bind("Seasonal") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using Microsoft.SharePoint;
namespace SampleProject.EditGridViewP2
{
public partial class EditGridViewP2UserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Select the current site, assuming the list is in this site.
SPWeb thisWeb = SPContext.Current.Web;
SPQuery query = new SPQuery();
//The list name is Starbucks.
SPList thisList = thisWeb.Lists["Starbucks"];
SPListItemCollection queryResults = thisList.GetItems(query);
//Construct a data table.
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Size", typeof(string));
dt.Columns.Add("Calories", typeof(int));
dt.Columns.Add("Seasonal", typeof(string));
//Code to fill the DataTable goes here; I’ll omit it to save some space.
foreach (SPListItem item in queryResults) {
DataRow dr = dt.NewRow();
dr["ID"] = Convert.ToInt32(item["ID"].ToString());
dr["Title"] = item["Title"] != null ? item["Title"].ToString() : "";
dr["Size"] = item["Size"] != null ? item["Size"].ToString() : "";
dr["Calories"] = item["Calories"] != null ? Convert.ToInt32(item["Calories"].ToString()) : 0;
if (item["Seasonal"] != null)
{
if (Convert.ToBoolean(item["Seasonal"]))
dr["Seasonal"] = "Yes";
else dr["Seasonal"] = "No";
}
else dr["Seasonal"] = "";
dt.Rows.Add(dr);
} //end foreach
//Persist the table in a Session object.
Session["StarbucksData"] = dt;
//Remember, earlier we set AutoGenerateColumns to true,
//so there’s no need to define the columns in the code.
StarbucksGridView.DataSource = dt;
StarbucksGridView.DataBind();
}
} //end Page_Load
private void Bind_Data()
{
//Bind to flashed table
StarbucksGridView.DataSource = Session["StarbucksData"];
StarbucksGridView.DataBind();
} //end Bind_Data
protected void Row_Databound(object sender, GridViewRowEventArgs e)
{
//First check if the row is in Edit mode.
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
//Find the dropdown control
DropDownList ddl = (DropDownList)e.Row.FindControl("SizeDropDownList");
//Retrieve the data from the session object.
DataTable ds = (DataTable)Session["StarbucksData"];
string selectedSize = ds.Rows[e.Row.RowIndex]["Size"].ToString();
//Get the choices for the DropDownList.
SPWeb thisWeb = SPContext.Current.Web;
//The Sample Choices List contains our data for the dropdown.
SPList choiceList = thisWeb.Lists["DrinkSize"];
SPQuery queryC = new SPQuery();
DataTable choices = new DataTable();
choices = choiceList.GetItems(queryC).GetDataTable();
//Bind the data to the DropDownList
ddl.DataSource = choices;
ddl.DataTextField = "Title";
ddl.DataValueField = "Title";
ddl.SelectedValue = selectedSize;
ddl.DataBind();
//Next the Seasonal Control
RadioButtonList rbl = (RadioButtonList)e.Row.FindControl("SeasonalRadioButtonList");
//Retrieve the data from the session object.
string selectedSeasonal = ds.Rows[e.Row.RowIndex]["Seasonal"].ToString();
if (selectedSeasonal.Equals("Yes"))
rbl.Items.FindByText("Yes").Selected = true;
else if (selectedSeasonal.Equals("No"))
rbl.Items.FindByText("No").Selected = true;
}
}
} //end Row_Databound
protected void Edit_Row(object sender, GridViewEditEventArgs e)
{
//Set the index of the row to be edited.
StarbucksGridView.EditIndex = e.NewEditIndex;
//Bind data to the GridView control.
Bind_Data();
} //end Edit_Row
protected void Cancel_Edit(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
StarbucksGridView.EditIndex = -1;
//Bind data to the GridView control.
Bind_Data();
} //end Cancel_Edit
protected void Update_Row(object sender, GridViewUpdateEventArgs e)
{
//Get the updated values from the controls.
GridViewRow row = StarbucksGridView.Rows[e.RowIndex];
DropDownList titleC = (DropDownList)row.FindControl("TitleDDL");
string id = ((Label)row.FindControl("IDTextBox")).Text;
string title = ((TextBox)row.FindControl("TitleTextBox")).Text;
string size = ((DropDownList)row.FindControl("SizeDropDownList")).SelectedValue;
string calories = ((TextBox)row.FindControl("CaloriesTextBox")).Text;
string seasonal = ((RadioButtonList)row.FindControl("SeasonalRadioButtonList")).SelectedValue;
//Retrieve the data from the Session object.
DataTable ds = (DataTable)Session["StarbucksData"];
//Update the values in the Session table.
ds.Rows[row.DataItemIndex]["ID"] = Convert.ToInt32(id);
ds.Rows[row.DataItemIndex]["Title"] = title;
ds.Rows[row.DataItemIndex]["Size"] = size;
ds.Rows[row.DataItemIndex]["Calories"] = Convert.ToInt32(calories);
if(Convert.ToBoolean(seasonal))
ds.Rows[row.DataItemIndex]["Seasonal"] = "Yes";
else ds.Rows[row.DataItemIndex]["Seasonal"] = "No";
//Update the values in the SharePoint List.
SPWeb thisWeb = SPContext.Current.Web;
SPList thisList = thisWeb.Lists["Starbucks"];
SPListItem item = thisList.GetItemById(Convert.ToInt32(id));
item["Title"] = title;
item["Size"] = size;
item["Calories"] = Convert.ToInt32(calories);
item["Seasonal"] = Convert.ToBoolean(seasonal);
item.Update();
//Reset the edit index.
StarbucksGridView.EditIndex = -1;
//Bind data to the GridView control.
Bind_Data();
} //end Update_Row
}
}
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.