Thursday, 9 October 2014

Edit, Update, Delete in SharePoint 2013 List using GridView.

In this article am going to discuss about GridView insert, edit, delete, update operations by using C# in SharePoint 2013.
By using .aspx code we can create like below.

When we deploy it will fetch the data from the list which we are assigned like below.
This is the method to bind data to gridview.

public void Bind() {
  try 
 {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                { using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists.TryGetList("Details");
                        SPListItemCollection coll = list.GetItems();
                        DataTable dt = coll.GetDataTable();
                        grdcrud.DataSource = dt;
                        grdcrud.DataBind();
                     }
                 }
            }
            catch (Exception ex)
            {   
                  Label1.Text = ex.ToString(); 
            }   
         }

Adding Items:-


Click on “Add” button to add the records to the list.

protected void lnkAdd_Click(object sender, EventArgs e)
        { 
            grdcrud.FooterRow.Visible = true;
            lnkAdd.Visible = false;
         }

Fill the necessary data and better make Id as auto generated, then click on "Insert" button to add the item to the list.

"Insert" is button but can't generate "Insert_Click" event because we have used in gridview column so we need to access by using "RowCommand" event like below'

protected void grdcrud_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
        {
            try 
           {
                if (e.CommandName.Equals("Insert"))
                {  
                     using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                    {   
                         using (SPWeb web = site.OpenWeb())
                        {                          
TextBox name = (TextBox)grdcrud.FooterRow.Cells[1].FindControl("txtNewName");
DropDownList dept = (DropDownList)grdcrud.FooterRow.Cells[2].FindControl("ddlNewDept");
TextBox sal = (TextBox)grdcrud.FooterRow.Cells[3].FindControl("txtNSal");
SPList list = web.Lists.TryGetList("Details");
                            //Auto Gen  id//
                            SPListItemCollection coll = list.GetItems();
                            DataTable dt = coll.GetDataTable();
                            int i = dt.Rows.Count;//
                            SPListItem item = list.Items.Add();
                            item["EmpId"] = i+1;
                            item["Name"] = name.Text;
                            item["Dept"] = dept.Text;
                            item["Sal"] = sal.Text;
                            item.Update();
                            Bind();
                        }   
                   }
               }
            }
            catch (Exception ex)  
           {
                Label1.Text = ex.ToString();   
            }
     }

Item Updating:-

Click on “Edit” to update the record.

Whenever you click the "Edit" button it will fires an event called "RowEditing", we have to make the item editable in text-box like above.

protected void grdcrud_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
        {
            try   
           {
                grdcrud.EditIndex = e.NewEditIndex;
                Bind(); 
            }
            catch (Exception ex)
            {    
                   Label1.Text = ex.ToString();            
             }
        }

After doing modifications we have to click "Update" button then it will fires an event called "RowUpdating", then we have to write required code to update data.

protected void grdcrud_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
        {
            try  
           {             
                Label id = (Label)grdcrud.Rows[e.RowIndex].Cells[0].FindControl("lblId");
TextBox name = (TextBox)grdcrud.Rows[e.RowIndex].Cells[1].FindControl("txtName");
DropDownList dept = (DropDownList)grdcrud.Rows[e.RowIndex].Cells[2].FindControl("ddlDept");
TextBox sal = (TextBox)grdcrud.Rows[e.RowIndex].Cells[3].FindControl("txtSal");
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    UpdateRow(id.Text, name.Text, dept.SelectedValue, int.Parse(sal.Text));
                    grdcrud.EditIndex = -1;
                    Bind(); 
                 });
            }
            catch (Exception ex)
            {  
                 Label1.Text = ex.ToString();   
             }   
       }

Implement separate method to Update the row, send the arguments as required.

public void UpdateRow(string Id,string name,string dept,int sal)
        {  using (SPSite site = new SPSite(SPContext.Current.Web.Url))
            {   using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists.TryGetList("Details");
                    SPListItem item = list.GetItemById(int.Parse(Id));
                    web.AllowUnsafeUpdates = true;
                    item["Name"] = name;
                    item["Dept"] = dept;
                    item["Sal"] = sal;
                    item.Update();
                    list.Update();
                    web.AllowUnsafeUpdates = false;
                }
            }
       }

If we want to keep the old data only then click on "Cancel" button, it will generate an event called "RowCancelingEdit" we have to write required code like below.

protected void grdcrud_RowCancelingEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
        {
            try
           {
                grdcrud.EditIndex = -1;
                Bind();
            }
            catch (Exception ex)
            {   
                Label1.Text = ex.ToString();
             }
         }

Item Deleting:-

Click on the “Delete” button to delete the record.

Declare one class level variable to get the selected item Id to Delete method.

string itemId;
protected void grdcrud_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
        {
            try
           {
                itemId = grdcrud.DataKeys[e.RowIndex].Value.ToString();
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    DeleteRow(itemId);
                    Bind();
                });
            }
            catch (Exception ex)
            {  
                  Label1.Text = ex.ToString();
             }
        }

Implemented separate method to delete an item by passing the Id as parameter like below.

public void DeleteRow(string ItemId)
        {  using (SPSite site = new SPSite(SPContext.Current.Web.Url))
            {   using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists.TryGetList("Details");
                    SPListItem item = null;
                    item = list.GetItemById(int.Parse(ItemId));
                    web.AllowUnsafeUpdates = true;
                    item.Delete();
                    list.Update();
                    web.AllowUnsafeUpdates = false;
                }
            }
        }

.aspx code:-

 <asp:GridView ID="grdcrud" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" EnableModelValidation="true” OnRowCancelingEdit="grdcrud_RowCancelingEdit" OnRowEditing="grdcrud_RowEditing" OnRowUpdating="grdcrud_RowUpdating"             OnRowCommand="grdcrud_RowCommand" ShowFooter="false" OnRowDeleting="grdcrud_RowDeleting" Width="500px">
 <Columns>
            <asp:TemplateField HeaderText="ID" HeaderStyle-HorizontalAlign="Left" >
                <EditItemTemplate>
                    <asp:Label ID="lblId" runat="server" Text='<%# Bind("EmpId") %>'></asp:Label>
                </EditItemTemplate>
  <ItemTemplate>
                    <asp:Label ID="lblNId" runat="server" Text='<%# Bind("EmpId") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name" HeaderStyle-HorizontalAlign="Left">
                <EditItemTemplate>
                    <asp:TextBox ID="txtName" Width="100" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtNewName" Width="100" runat="server" ></asp:TextBox>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Dept" HeaderStyle-HorizontalAlign="Left">
                <EditItemTemplate>
                    <asp:DropDownList ID="ddlDept" runat="server" SelectedValue='<%# Bind("Dept") %>'>
                        <asp:ListItem Value="Dev" Text="Dev"></asp:ListItem>
                        <asp:ListItem Value="Testing" Text="Testing"></asp:ListItem>
                        <asp:ListItem Value="HR" Text="HR"></asp:ListItem>
                        <asp:ListItem Value="Admin" Text="Admin"></asp:ListItem>
                      
                    </asp:DropDownList>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblDept" runat="server" Text='<%# Bind("Dept") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    <asp:DropDownList ID="ddlNewDept" runat="server" >
                        <asp:ListItem Value="Dev" Text="Dev"></asp:ListItem>
                        <asp:ListItem Value="Testing" Text="Testing"></asp:ListItem>
                        <asp:ListItem Value="HR" Text="HR"></asp:ListItem>
                        <asp:ListItem Value="Admin" Text="Admin"></asp:ListItem>
                    </asp:DropDownList>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Salary" HeaderStyle-HorizontalAlign="Left">
                <EditItemTemplate>
                    <asp:TextBox ID="txtSal" Width="100" runat="server" Text='<%#Bind("Sal") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblSal" runat="server" Text='<%# Bind("Sal") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtNSal" Width="100" runat="server"></asp:TextBox>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Edit" ShowHeader="False" HeaderStyle-HorizontalAlign="Left">
                <EditItemTemplate>
                    <asp:LinkButton ID="lbkUpdate" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
                    <asp:LinkButton ID="lnkCancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:LinkButton ID="lnkAdd" runat="server" CausesValidation="False" CommandName="Insert" Text="Insert"></asp:LinkButton>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:LinkButton ID="lnkEdit" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
       <asp:CommandField HeaderText="Delete" HeaderStyle-HorizontalAlign="Left" ShowDeleteButton="True" ShowHeader="True" />
        </Columns>
            <AlternatingRowStyle BackColor="#99ccff"/>
        </asp:GridView>
        <asp:LinkButton ID="lnkAdd" runat="server" OnClick="lnkAdd_Click">Add</asp:LinkButton>
<asp:Label ID="Label1" runat="server" ></asp:Label>


Thank You....!


25 comments:

  1. Hello

    Can you share the complete source code.!!

    Thanks in Advance.

    Vikram

    ReplyDelete