Search This Blog

Thursday, March 12, 2015

Save Update Delete Record From GridView in List Using Footer For Insertion



 1- Create Two list -
       Country LookUp  ------Title(India,England,UAE..)   
       Global Clients  ------Title (ClientName),Country,CountryID

Create A Visual web part

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ 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" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="IEUDDLGridUserControl.ascx.cs" Inherits="EUDGridView.IEUDDLGrid.IEUDDLGridUserControl" %>
<asp:GridView ID="dgvDDLBindsample" runat="server" AutoGenerateColumns="False" Width="600px"
    CellPadding="4" EnableModelValidation="True" ForeColor="#333333"
    GridLines="None"   ShowFooter="true"
     AutoGenerateEditButton="false"
     DataKeyNames="ID">
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:TemplateField HeaderText="ItemID" Visible="false" HeaderStyle-HorizontalAlign="Left">
            <ItemTemplate>
                <%# Eval("ID") %>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Label ID="lblItemID" runat="server" Text='<%# Eval("ID") %>' Columns="3" />
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Client Name" HeaderStyle-HorizontalAlign="Left">
            <ItemTemplate>
                <%# Eval("Title") %>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtTitle" Width="120px" runat="server" Text='<%# Eval("Title") %>' Columns="3" />
            </EditItemTemplate>
             <FooterTemplate>
              <asp:TextBox ID="txtTitle" Width="120px" runat="server"></asp:TextBox>
             
           </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Country" HeaderStyle-HorizontalAlign="Left">
            <ItemTemplate>
                <%# Eval("Country") %>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:DropDownList ID="ddlCountry" Width="180px" runat="server"></asp:DropDownList>
                <asp:Label ID="lblCountryId" runat="server" Text='<%# Bind("CountryID") %>' Visible="false"></asp:Label>
            </EditItemTemplate>
            <FooterTemplate>
              <asp:DropDownList ID="ddlCountry" runat="server" Width="180px" TabIndex="2">
              </asp:DropDownList>
           </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Action" ShowHeader="False" HeaderStyle-HorizontalAlign="Left"
                                    HeaderStyle-Width="90px">
                                    <EditItemTemplate>
                                        <asp:LinkButton ID="lnkUpdate" runat="server" CausesValidation="True"  OnClick="lnkUpdate_Click"
                                            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="True" OnClick="lnkInsert_Click" TabIndex="4"
                                            ValidationGroup="Insert" Text="Save"></asp:LinkButton>
                                      
                                    </FooterTemplate>
                                    <ItemTemplate>
                                        <asp:LinkButton ID="lnkEdit" runat="server" CausesValidation="False" CommandName="Edit"
                                            Text="Edit"></asp:LinkButton>
                                    </ItemTemplate>
                                    <HeaderStyle HorizontalAlign="Left" />
                                   
                                     <ItemStyle Width="90px"></ItemStyle>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Delete" ShowHeader="False" HeaderStyle-HorizontalAlign="Left"
                                    HeaderStyle-Width="90px">
                                    <ItemTemplate>
                                     <asp:LinkButton ID="lnkDelete" runat="server" CausesValidation="True" OnClick="lnkdelete_Click"
                                            Text="Delete" ValidationGroup="Insert"></asp:LinkButton>
                                 
                                   </ItemTemplate>
                                    <HeaderStyle HorizontalAlign="Left" />
                                   <ItemStyle Width="90px"></ItemStyle>
                                </asp:TemplateField>
    </Columns>
    <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
</asp:GridView>
<asp:Label ID="lblMessage" runat="server"></asp:Label>



CS  Code


using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Security;
namespace EUDGridView.IEUDDLGrid
{
    public partial class IEUDDLGridUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            dgvDDLBindsample.RowDataBound += new GridViewRowEventHandler(dgvDDLBindsample_RowDataBound);
            dgvDDLBindsample.RowEditing += new GridViewEditEventHandler(dgvDDLBindsample_RowEditing);
            //dgvDDLBindsample.RowUpdating += new GridViewUpdateEventHandler(dgvDDLBindsample_RowUpdating);
            //dgvDDLBindsample.RowDeleting += new GridViewDeleteEventHandler(dgvDDLBindsample_RowDeleting);
            dgvDDLBindsample.RowCancelingEdit += new GridViewCancelEditEventHandler(dgvDDLBindsample_RowCancelingEdit);
            if (!IsPostBack)
            {
                getData();
                FillCountryDropDown();
            }
        }

        void dgvDDLBindsample_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowState == DataControlRowState.Edit || (e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate)))
                {

                    SPWeb currentWeb = SPContext.Current.Web;
                    SPList lst = currentWeb.Lists["Country LookUp"];
                    SPQuery sQuery = new SPQuery();
                    sQuery.Query = "<OrderBy><FieldRef Name='ID' /></OrderBy>";
                    SPListItemCollection myColl = lst.GetItems(sQuery);
                    DropDownList ddlCountryNew = e.Row.FindControl("ddlCountry") as DropDownList;
                    if (myColl.Count > 0)
                    {
                        ddlCountryNew.DataValueField = "ID";
                        ddlCountryNew.DataTextField = "Title";
                        ddlCountryNew.DataSource = myColl.GetDataTable();
                        ddlCountryNew.DataBind();
                    }
                    ddlCountryNew.Items.Insert(0, new ListItem("--Select Country--"));


                    int strItemID = int.Parse(dgvDDLBindsample.DataKeys[e.Row.RowIndex].Value.ToString());
                    SPList lstGlobalClients = currentWeb.Lists["Global Clients"];
                    SPQuery strFindLookUpValue = new SPQuery();
                    strFindLookUpValue.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>"+strItemID+"</Value></Eq></Where>";
                    SPListItemCollection GlobalClientsColl = lstGlobalClients.GetItems(strFindLookUpValue);
                    if (GlobalClientsColl.Count > 0)
                    {
                        SPListItem item = GlobalClientsColl[0];
                        SPFieldLookupValue value = new SPFieldLookupValue(item["CountryID"].ToString());
                        for (int i = 0; i < ddlCountryNew.Items.Count; i++)
                        {
                            if (value.LookupId.ToString() == ddlCountryNew.Items[i].Value)
                            {
                                ddlCountryNew.SelectedIndex = i;
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                lblMessage.Text = Ex.ToString();
            }



        }
        public void updateRow(string ItemID1, string Title, string CountryLookUP, int CountryLookUPID)
        {
            SPWeb currentWeb = SPContext.Current.Web;
            SPList lst = currentWeb.Lists["Global Clients"];
            SPListItem item = null;
            item = lst.GetItemById(int.Parse(ItemID1));
            item["Title"] = Title;
            item["Country"] = CountryLookUP;
            item["CountryID"] = CountryLookUPID;
            currentWeb.AllowUnsafeUpdates = true;
            item.Update();
            lst.Update();
            currentWeb.AllowUnsafeUpdates = false;

        }
        public void getData()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWeb currentWeb = SPContext.Current.Web;
                    SPList lst = currentWeb.Lists["Global Clients"];
                    SPQuery sQuery = new SPQuery();
                    sQuery.Query = "<OrderBy><FieldRef Name='ID' /></OrderBy>";
                    SPListItemCollection myColl = lst.GetItems(sQuery);
                    if (myColl.Count > 0)
                    {
                        dgvDDLBindsample.DataSource = myColl.GetDataTable();
                        dgvDDLBindsample.DataBind();
                    }
                });
            }
            catch (Exception Ex)
            {

                lblMessage.Text = Ex.ToString();
            }
        }



        void dgvDDLBindsample_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                dgvDDLBindsample.EditIndex = -1;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    getData();
                    FillCountryDropDown();
                });
            }
            catch (Exception Ex)
            {
                lblMessage.Text = Ex.ToString();
            }
        }

        void dgvDDLBindsample_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                Label lbl = (Label)dgvDDLBindsample.Rows[e.RowIndex].Cells[1].FindControl("lblItemID");
                TextBox txtTitle1 = (TextBox)dgvDDLBindsample.Rows[e.RowIndex].Cells[2].FindControl("txtTitle");
                DropDownList ddlCountryNew = (DropDownList)dgvDDLBindsample.Rows[e.RowIndex].Cells[3].FindControl("ddlCountry");
                int LookUpValue = int.Parse(ddlCountryNew.SelectedValue.ToString());
                string LookUpValue1 = ddlCountryNew.SelectedItem.ToString();
                updateRow(lbl.Text, txtTitle1.Text, LookUpValue1, LookUpValue);
                dgvDDLBindsample.EditIndex = -1;
                getData();
                FillCountryDropDown();
               
            }
            catch (Exception Ex)
            {
                lblMessage.Text = Ex.ToString();
            }
        }
       
        //protected void dgvDDLBindsample_RowDeleting(object sender, GridViewDeleteEventArgs e)
        //{
           
        //}

        public void DeleteRow(string ItemIDNew)
        {
            SPWeb currentWeb = SPContext.Current.Web;
            SPList lst = currentWeb.Lists["Global Clients"];
            SPListItem item = null;
            item = lst.GetItemById(int.Parse(ItemIDNew));
            currentWeb.AllowUnsafeUpdates = true;
            item.Delete();
            lst.Update();
            currentWeb.AllowUnsafeUpdates = false;

        }
        void dgvDDLBindsample_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                dgvDDLBindsample.EditIndex = e.NewEditIndex;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    getData();
                    FillCountryDropDown();
                });
            }
            catch (Exception Ex)
            {
                lblMessage.Text = Ex.ToString();
            }
        }
        protected void lnkInsert_Click(object sender, EventArgs e)
        {
            SPWeb currentWeb = SPContext.Current.Web;
            SPList lst = currentWeb.Lists["Global Clients"];
            SPListItemCollection myColl = lst.Items;
            TextBox txtTitle = (TextBox)dgvDDLBindsample.FooterRow.FindControl("txtTitle");
            DropDownList ddlCountryNew = (DropDownList)dgvDDLBindsample.FooterRow.FindControl("ddlCountry");

            if (txtTitle.Text != "" || ddlCountryNew.SelectedItem.ToString() != "--Select Country--")
            {
                int strCounrtyId = int.Parse(ddlCountryNew.SelectedValue.ToString());
                string strContryName = ddlCountryNew.SelectedItem.ToString();
                SPListItem item = myColl.Add();
                item["Title"] = txtTitle.Text;
                item["Country"] = strContryName;
                item["CountryID"] = strCounrtyId;
                item.Update();
                txtTitle.Text = "";
                getData();
                FillCountryDropDown();
                lblMessage.Text = "Save Record Successfully?";
            }
           
           
        }
        protected void lnkUpdate_Click(object sender, EventArgs e)
        {
            LinkButton lnkbtn = sender as LinkButton;
            GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
            try
            {
                Label lbl = (Label)dgvDDLBindsample.Rows[gvrow.RowIndex].Cells[1].FindControl("lblItemID");
                TextBox txtTitle1 = (TextBox)dgvDDLBindsample.Rows[gvrow.RowIndex].Cells[2].FindControl("txtTitle");
                DropDownList ddlCountryNew = (DropDownList)dgvDDLBindsample.Rows[gvrow.RowIndex].Cells[3].FindControl("ddlCountry");
                int LookUpValue = int.Parse(ddlCountryNew.SelectedValue.ToString());
                string LookUpValue1 = ddlCountryNew.SelectedItem.ToString();
                updateRow(lbl.Text, txtTitle1.Text, LookUpValue1, LookUpValue);
                dgvDDLBindsample.EditIndex = -1;
                getData();
                FillCountryDropDown();
                lblMessage.Text = "Update  Record Succesfully?";
            }
            catch (Exception Ex)
            {
                lblMessage.Text = Ex.ToString();
            }
            //if (((TextBox)gvEG.Rows[gvrow.RowIndex].FindControl("txtCoaching")).Text == "")
            //{
            //    str = str + Convert.ToString(GetLocalResourceObject("rfvCoaching")) + "<br>";
            //    mstCoachingRequiredField = true;
            //}
           

        }

        protected void lnkdelete_Click(object sender, EventArgs e)
        {
            string strItemID1;
            LinkButton lnkbtn = sender as LinkButton;
            GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
            try
            {
                strItemID1 = dgvDDLBindsample.DataKeys[gvrow.RowIndex].Value.ToString();
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    DeleteRow(strItemID1);
                    getData();
                    FillCountryDropDown();
                    lblMessage.Text = "Delete Record Succesfully?";
                });
            }
            catch (Exception ex)
            {

                Response.Write(ex.ToString());
            }
           
        }
        protected void FillCountryDropDown()
        {
            SPWeb currentWeb = SPContext.Current.Web;
            SPList lst = currentWeb.Lists["Country LookUp"];
            SPQuery sQuery = new SPQuery();
            sQuery.Query = "<OrderBy><FieldRef Name='ID' /></OrderBy>";
            SPListItemCollection myColl = lst.GetItems(sQuery);
            DropDownList ddlCountryNew =dgvDDLBindsample.FooterRow.FindControl("ddlCountry") as DropDownList;
            if (myColl.Count > 0)
            {
                ddlCountryNew.DataValueField = "ID";
                ddlCountryNew.DataTextField = "Title";
                ddlCountryNew.DataSource = myColl.GetDataTable();
                ddlCountryNew.DataBind();
            }
            ddlCountryNew.Items.Insert(0, new ListItem("--Select Country--"));

        }

       
    }
}




No comments:

Post a Comment