Showing posts with label GridView editing tutorial. Show all posts
Showing posts with label GridView editing tutorial. Show all posts

Thursday, 22 January 2026

Add ,Edit and Delete in GridView with People picker and DateTime Picker control

Add ,Edit and Delete in GridView with People picker and DateTime Picker control

using System;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.IO;
using System.Collections;
namespace CustomPageForLibrary.Layouts.CustomPageForLibrary
{
    public partial class TaskFormForLirary : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DropDownBind();
                BindData();
             
             
            }
        }
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
           
            GridView1.EditIndex = e.NewEditIndex;
            BindData();
        }
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int i = e.RowIndex;

            //using (SPSite site = new SPSite("siteurl"))
            using (SPSite site = new SPSite(SPContext.Current.Web.Url))
            {
                site.AllowUnsafeUpdates = true;
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPList list = web.Lists["MOMListt"];
                    int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
                    SPListItem item = list.GetItemById(id);
               
                  //  item["Meeting"] = new SPFieldLookupValue(Convert.ToInt32(txtMeetingId.Text),txtMeetingName.Text);
                    item["Minutes"] = ((TextBox)GridView1.Rows[i].FindControl("txtMinutes")).Text;
                    PeopleEditor ppAuthor = ((PeopleEditor)GridView1.Rows[i].FindControl("ActionByUser"));
                    PickerEntity ActionUser = (PickerEntity)ppAuthor.ResolvedEntities[0];
                    SPUser actionByUser = Web.EnsureUser(ActionUser.Key);
                    item["Actionby"] = actionByUser;
                    if (((DateTimeControl)GridView1.Rows[i].FindControl("targetdateuser")).SelectedDate.Date.ToString() != "" || ((DateTimeControl)GridView1.Rows[i].FindControl("targetdateuser")).SelectedDate.Date.ToString() !=null)
                    {
                    item["TargetDate"] = ((DateTimeControl)GridView1.Rows[i].FindControl("targetdateuser")).SelectedDate.Date;
                    }
                    item["Status"] = ((DropDownList)GridView1.Rows[i].FindControl("DropDownList1")).SelectedItem.Text;
                    CheckBox chk = ((CheckBox)GridView1.Rows[i].FindControl("Assigned"));
                    string blActive = "";
                    if (chk.Checked == true)
                    {
                        blActive = "True";
                        item["assignedtask"] = blActive;
                    }
                    else
                    {
                        blActive = "False";
                        item["assignedtask"] = blActive;
                    }
                    item["Issues"] = TextBox7.Text;
                    item.Update();
                    web.AllowUnsafeUpdates = false;
                }
                site.AllowUnsafeUpdates = false;

            }
            GridView1.EditIndex = -1;
            BindData();
        }
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DataRowView drview = e.Row.DataItem as DataRowView;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    SPSite site = new SPSite(SPContext.Current.Web.Url);
                    SPWeb web = site.OpenWeb();
                    PeopleEditor pplEditor = ((PeopleEditor)e.Row.FindControl("ActionByUser"));
                    ArrayList alApprover = new ArrayList();
                    PickerEntity pentApprover = new PickerEntity();
                    char[] delimiterChars = { '#' };
                    string text = drview[2].ToString();
                    string[] words = text.Split(delimiterChars);
                    pentApprover.Key = words[1];
                    alApprover.Add(pentApprover);
                    pplEditor.UpdateEntities(alApprover);
                    DateTimeControl dtc = ((DateTimeControl)e.Row.FindControl("targetdateuser"));
                    dtc.SelectedDate=Convert.ToDateTime(drview[3].ToString());
                    DropDownList dpEmpdept = (DropDownList)e.Row.FindControl("DropDownList1");
                    DataTable dt = GetStatus();
                    dpEmpdept.DataSource = GetStatus();
                    dpEmpdept.DataTextField = "DepName";
                    dpEmpdept.DataValueField = "DepName";
                    dpEmpdept.DataBind();
                    dpEmpdept.SelectedValue = drview[4].ToString();
                    CheckBox chkb = (CheckBox)e.Row.FindControl("Assigned");
                    if (drview[5].ToString() == "True")
                    { chkb.Checked = true; }
                    else { chkb.Checked = false; }
             
                }
            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                DropDownList dp = (DropDownList)e.Row.FindControl("DropDownList14");
                dp.DataSource = GetStatus();
                dp.DataTextField = "DepName";
                dp.DataValueField = "DepName";
                dp.DataBind();
            }
        }
        private DataTable GetStatus()
        {
           
            DataTable dt = new DataTable();
            dt.Columns.Add("DepName");
            DataRow rw1 = dt.NewRow();
            rw1[0] = "Open";
            dt.Rows.Add(rw1);
            DataRow rw2 = dt.NewRow();
            rw2[0] = "Closed";
            dt.Rows.Add(rw2);
            return dt;
        }
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;

            BindData();

        }
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int i = e.RowIndex;
           // BindData();
        }
        public void BindData()
        {
            using (SPSite s = new SPSite(SPContext.Current.Web.Url))
            {
                using (SPWeb sw = s.OpenWeb())
                {
                    SPList sl = sw.Lists["MOMListt"];
                    SPQuery query=new SPQuery();
                    if (txtMeetingId.Text != "")
                    {
                        query.Query = @"<Where>" +
          "<Eq>" +
             "<FieldRef Name='Meeting' LookupId='True' />" +
             "<Value Type='Lookup'>" + Convert.ToInt32(txtMeetingId.Text) + "</Value>" +
          "</Eq>" +
       "</Where>";
                    }
                    SPListItemCollection itemCollection = sl.GetItems(query);
                    DataTable ResTable = new DataTable();
                    ResTable.Columns.Add(new DataColumn("ID"));
                    ResTable.Columns.Add(new DataColumn("Minutes"));
                    ResTable.Columns.Add(new DataColumn("Actionby"));
                    ResTable.Columns.Add(new DataColumn("TargetDate"));
                    ResTable.Columns.Add(new DataColumn("Status"));
                    ResTable.Columns.Add(new DataColumn("TaskAssigned"));
               
                    foreach (SPListItem item in itemCollection)
                    {
                        DataRow dr = ResTable.NewRow();
                        dr["ID"] = item["ID"].ToString();
                        dr["Minutes"] = item["Minutes"];
                        dr["ActionBy"] = item["Actionby"].ToString();
                        dr["TargetDate"] = item["TargetDate"];
                        dr["Status"] = item["Status"].ToString();
                        dr["TaskAssigned"] = item["assignedtask"].ToString();
                        ResTable.Rows.Add(dr);
                    }
                    if (ResTable.Rows.Count > 0)
                    {
                        GridView1.DataSource = ResTable;
                        GridView1.DataBind();
                     
                    }
                    else
                    {
                        DataRow dr = ResTable.NewRow();
                        dr["ID"] = "";
                        dr["Minutes"] = "";
                        dr["ActionBy"] = "";
                        dr["TargetDate"] = "";
                        dr["Status"] = "";
                        dr["TaskAssigned"] = "";
                        ResTable.Rows.Add(dr);
                        GridView1.DataSource = ResTable;
                        GridView1.DataBind();
                    }
                 
                }
            }
        }
     
       
        public void DropDownBind()
        {
            using (SPSite site = new SPSite(SPContext.Current.Web.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    DataSet ds = new DataSet();
                    SPList list = web.Lists["Board Events"];
                    SPListItem item = list.Items.GetItemById(Convert.ToInt32(Request.QueryString["Mid"].ToString()));
                    txtMeetingName.Text = item["Title"].ToString();
                    txtMeetingId.Text = item["ID"].ToString();
                 
                }
            }
        }
     
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Add")
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    site.AllowUnsafeUpdates = true;
                    using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        SPList list = web.Lists["MOMListt"];
                        SPListItem item = list.Items.Add();
                        item["Meeting"] = new SPFieldLookupValue(Convert.ToInt32(txtMeetingId.Text), txtMeetingName.Text);
                        item["Minutes"] = ((TextBox)GridView1.FooterRow.FindControl("txtMinuteFooter")).Text;
                        PeopleEditor ppAuthor = ((PeopleEditor)GridView1.FooterRow.FindControl("ActionBy"));
                        PickerEntity ActionUser = (PickerEntity)ppAuthor.ResolvedEntities[0];
                        SPUser actionByUser = Web.EnsureUser(ActionUser.Key);
                        item["Actionby"] = actionByUser;
                        item["TargetDate"] = ((DateTimeControl)GridView1.FooterRow.FindControl("targetdate")).SelectedDate.Date;
                        item["Status"] = ((DropDownList)GridView1.FooterRow.FindControl("DropDownList14")).SelectedItem.Text;
                        CheckBox chk = ((CheckBox)GridView1.FooterRow.FindControl("AssignedFilter"));
                        string blActive = "";
                        if (chk.Checked == true)
                        {
                            blActive = "True";
                            item["assignedtask"] = blActive;
                        }
                        else
                        {
                            blActive = "False";
                            item["assignedtask"] = blActive;
                        }
                        if (TextBox7.Text != "")
                        {
                            item["Issues"] = TextBox7.Text;
                        }
                        item.Update();
                        web.AllowUnsafeUpdates = false;
                    }
                    site.AllowUnsafeUpdates = false;
               
                }
                BindData();
            }
            else if (e.CommandName == "Delete")
         {
             using (SPSite site = new SPSite(SPContext.Current.Web.Url))
           {
                site.AllowUnsafeUpdates = true;
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                 
                    SPList taskList = web.Lists["Tasks"];
                    SPQuery query = new SPQuery();
                    query.Query = @"<Where>" +
         "<Eq>" +
            "<FieldRef Name='MinuteofMeetingId'/>" +
            "<Value Type='Number'>" + Convert.ToInt32(e.CommandArgument.ToString()) + "</Value>" +
         "</Eq>" +
      "</Where>";

                    SPListItemCollection itemcollection = taskList.GetItems(query);

                    for (int i = itemcollection.Count - 1; i >= 0; i--)
                    {
                        SPListItem item = itemcollection[i];
                        item.Delete();
                    }
                    SPList list = web.Lists["MOMListt"];
                    list.Items.DeleteItemById(Convert.ToInt32(e.CommandArgument.ToString()));
                    web.AllowUnsafeUpdates = false;
                }
                site.AllowUnsafeUpdates = false;
           }
             BindData();
             
        }
         

        }
     

       
    }
}


HTML Code///////////////////////////////////////////////////////////////////////////////////////////////
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TaskFormForLirary.aspx.cs" Inherits="CustomPageForLibrary.Layouts.CustomPageForLibrary.TaskFormForLirary" DynamicMasterPageFile="~masterurl/default.master" %>

<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<style type="text/css">
        #DivContent
        {
            margin-top: 30px;
            width: 85%;
            border: .1em;
            border-style: none;
            padding: 15px;
        }
        table
        {
            width: 100%;
        }
        .ControlTD
        {
            width: 20%;
            text-align: left;
        }
        .TextTD
        {
            width: 25%;
            font-size: 12px;
            text-align: left;
            color: #00A1DE;
        }
        .RFVTD
        {
            width: 10%;
            text-align: left;
        }
        p
        {
            text-align: center;
            font-size: 22px;
            color: #3C8A2E;
        }
    </style>
    <script language="javascript" type="text/javascript">

        function ValidateGrid(x) {

            var gridView = document.getElementById('<%=GridView1.ClientID %>');

            var selectedRowIndex = x.parentNode.parentNode.rowIndex;

            var txtName = gridView.rows[parseInt(selectedRowIndex)].cells[0].children[0];

             var pplpicker = gridView.rows[parseInt(selectedRowIndex)].cells[1].children[0];

            if (txtName.value == "" || pplpicker.value=="")
            {

                alert('Please input all required fields');

                return false;

            }

        }

    </script>
</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">

<div id="DivContent">
        <p>
            Minutes of Meeting</p>
            <div><div>&nbsp; Meeting&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
               <%-- <asp:DropDownList ID="DropDownList2" runat="server" style="margin-left: 0px" Width="309px">
                </asp:DropDownList>--%>
                <asp:Label ID="txtMeetingName" runat="server"  Font-Bold="true">
                </asp:Label><asp:Label ID="txtMeetingId" runat="server"
                     ForeColor="White"></asp:Label>
                   
                </div></div>
                <asp:UpdatePanel ID="Panel" runat="server" >
            <ContentTemplate>
            <br />
            <br />
         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
    EnableModelValidation="True" ShowFooter="True" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowCommand="GridView1_RowCommand" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" OnRowDataBound="GridView1_RowDataBound"  >
    <Columns>
        <asp:TemplateField HeaderText="Minutes">
            <EditItemTemplate>
                <asp:TextBox ID="txtMinutes" runat="server" Text='<%#Eval("Minutes")%>' TextMode="MultiLine" Width="350px" Height="70px"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%#Eval("Minutes")%>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
         <asp:TextBox ID="txtMinuteFooter" runat="server" TextMode="MultiLine" Width="350px" Height="70px"></asp:TextBox>
     
        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Action By">
            <EditItemTemplate>
                <SharePoint:PeopleEditor ID="ActionByUser" runat="server" MultiSelect="false" Width="200px" AllowEmpty="false"  />
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%#Eval("ActionBy")%>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                 <SharePoint:PeopleEditor ID="ActionBy" runat="server" MultiSelect="false" Width="200px" AllowEmpty="false"  />
        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Target Date" ItemStyle-Width="150px">
            <EditItemTemplate>
           
                <SharePoint:DateTimeControl EnableViewState="true" ID="targetdateuser" runat="server"
                        DateOnly="true" />
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label3" runat="server" Text='<%#Eval("TargetDate")%>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                 <SharePoint:DateTimeControl EnableViewState="true" ID="targetdate" runat="server"
                        DateOnly="true" />
        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Status">
            <EditItemTemplate>
                <asp:DropDownList ID="DropDownList1" runat="server">
             
               
                </asp:DropDownList>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label4" runat="server" Text='<%#Eval("Status")%>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
         <asp:DropDownList ID="DropDownList14" runat="server">
             
                </asp:DropDownList>
        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Assigned Task">
            <EditItemTemplate>
               <asp:CheckBox ID="Assigned" runat="server">
             
                </asp:CheckBox>
            </EditItemTemplate>
            <ItemTemplate>
              <asp:Label ID="Label5" runat="server" Text='<%#Eval("TaskAssigned")%>'></asp:Label>
           
           
            </ItemTemplate>
            <FooterTemplate>
         <asp:CheckBox ID="AssignedFilter" runat="server" >
                </asp:CheckBox>
        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField ShowHeader="False">
            <EditItemTemplate>
                <asp:LinkButton ID="LinkButton11" runat="server" CausesValidation="true" OnClientClick='javascript:return ValidateGrid(this);'
                    CommandName="Update" Text="Update" CommandArgument='<%#Eval("ID")%>'></asp:LinkButton>
                &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
                    CommandName="Cancel" Text="Cancel"></asp:LinkButton>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
                    CommandName="Edit" Text="Edit"></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField ShowHeader="False">
            <ItemTemplate>
         
                <asp:LinkButton ID="LinkButton2s" runat="server" CausesValidation="False"
                    CommandName="Delete" Text="Delete" CommandArgument='<%#Eval("ID")%>'></asp:LinkButton>

            </ItemTemplate>
            <FooterTemplate>
             <asp:LinkButton ID="LinkButton21" runat="server"
                    CommandName="Add" Text="Add" CausesValidation="true" OnClientClick='javascript:return ValidateGrid(this);'></asp:LinkButton>
            </FooterTemplate>
        </asp:TemplateField>

    </Columns>
 
</asp:GridView>
    </ContentTemplate>
    </asp:UpdatePanel>
<div>
    <table>
        <tr>
            <td valign="top">Pending Issues :</td><td>
                <asp:TextBox ID="TextBox7" runat="server" TextMode="MultiLine" Height="84px" Width="534px"></asp:TextBox></td>

        </tr>

    </table>

</div>
        <br />
        <p>
            &nbsp;</p>
    </div>

</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Application Page
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
My Application Page
</asp:Content>