Saturday, 31 August 2013

GridView Edit/ Cancel/ Update/ Delete in ASP.net


GridView Editing / Updating / Deleting:



                     One of the feature of GridView is to support "in place Editing" what even data we are presenting to user can also be allowed with rich Editing (deleting also).

Gridview provides a property called EditIndex whose default value is "-1". When this value is changed to some record then that record of GridView is set to be in Editing Mode.

In Editing mode all fields of GridView provide different presentation.

BoundField --- displays data in Textboxes
TemplateField -- displays EditItemTemplate instead of ItemTemplate , CommandField displays Update, Cancel instead of Edit, Update option.


CommandField is one more GridViewField which is provide Exclusively for Editing purpose and which has different arguments and Events to support Editing. Combining all these fields along with Edit Index property will provide the required functionality.


Steps:


1) In a new form create Button ,Gridview and Write code under Button Click event to set Data Object to it.

2) Set Auto Generate Columns false . So, that we can specify our own column information.

Go to Source view and write code / markup for Gridview ensuring that they are with editing behavior.

3) For all command field buttons GridView provides events where we have to write our implementations .



Events Raised:


for Edit – RowEditing event
for Delete – RowDeleting event
for Update – RowUpdating event
for Cancel – RowCancelingEdit event



Source Code:




 <asp:GridView ID="GV" runat="server" AutoGenerateColumns="False" 
 ShowFooter="true" OnRowEditing="GV_OnRowEditing" 
OnRowDeleting="GV_OnRowDeleting"                   
OnRowCancelingEdit="GV_RowCancellingEdit" onrowupdating="GV_RowUpdating">

     <Columns>

        <asp:TemplateField HeaderText="Metal" >
            <ItemTemplate>
                <asp:Label ID="lblMat" runat="server" Text='<%#Eval("Mat") %>'/>
                <asp:Label ID="lblMat_Id" runat="server" Text='<%#Eval("Mat_Id") %>' Visible="false"/>
            </ItemTemplate>
       </asp:TemplateField>

       <asp:TemplateField HeaderText="Type" >
          <ItemTemplate>
              <asp:Label ID="lblItem" runat="server" Text='<%#Eval("Item_Type") %>'/>
              <asp:Label ID="lblItem_Id" runat="server" Text='<%
#Eval("Item_Id") %>' Visible="false"/>
          </ItemTemplate>
       </asp:TemplateField>

       <asp:TemplateField HeaderText="Unit"  >
           <ItemTemplate>
               <asp:Label ID="lblUnit" runat="server" Text='<%#Eval("Unit") %>'/>
          </ItemTemplate>
       </asp:TemplateField>

       <asp:TemplateField HeaderText="Qty"  >
         <ItemTemplate>
            <asp:Label ID="lblqty" runat="server" Text='<%#Eval
("Qty") %>'/>
         </ItemTemplate>
         <EditItemTemplate >
             <asp:TextBox ID="txtEditQty" runat="server" Text='<%
#Eval("Qty") %>' Width="100%"/>
         </EditItemTemplate>
      </asp:TemplateField>

      <asp:TemplateField HeaderText="Level" HeaderStyle-ForeColor="White">
           <ItemTemplate>
                <%#GetLevel(Eval("Mat"))%>
           </ItemTemplate>
           <FooterTemplate>
                <%#GetTotal()%>
           </FooterTemplate>
      </asp:TemplateField>
      <asp:CommandField ShowEditButton="True" ItemStyle-Width="15%"  />
      <asp:CommandField ShowDeleteButton="True" HeaderStyle-Width="10%" />

    </Columns>
</asp:GridView>



Code Behind:



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Web.Services;

public partial class GV : System.Web.UI.Page
{
    string Code;
    double UserId;
    string Web_Login;    
    string Result;
    int a;

    protected override void OnPreInit(EventArgs e)
    {
        base.OnPreInit(e);

        lntSPCurrentSite objCurrentSite = new lntSPCurrentSite();
        this.MasterPageFile = objCurrentSite.MasterURL;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        lntSPCurrentSite objCurrentSite = new lntSPCurrentSite();
        Design objDesign = new Design();

        Code = objCurrentSite.WebSiteName;
        
        lntSPCurrentUser objCurrentUser = new lntSPCurrentUser();

        Web_Login = objCurrentUser.LoginName;
        UserId = objDesign.UserId_For_EccWebLogin(Web_Login);

        if (!IsPostBack)
        {              
            Bind_Tender_Quantity_GV();            
        }
        
        
    }
    public string GetTotal()
    {
        return "Total:" + a.ToString();
    }

    public string GetLevel(object Material)
    {
        a++;
        if (Material.ToString().ToUpper().Contains("RCC"))
            return "high";
        else
            return "low";
    }
    protected void Bind_GV()
    {
        Design obj = new Design();
        DataSet ds = //data;
        GV.DataSource = ds;
        GV.DataBind();

    }

    protected void GV_OnRowEditing(object sender, GridViewEditEventArgs e)
    {
        GV.EditIndex = e.NewEditIndex;

        Bind_GV();
    }
    protected void GV_RowCancellingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GV.EditIndex = -1;

        Bind_GV();
    }
    protected void GV_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Design obj = new Design();

        GridViewRow row = (GridViewRow)GV.Rows[e.RowIndex];
        string Mat_Id = ((Label)row.FindControl("lblMat_Id")).Text;
        string Grade_Id = //fetch data
        string Item_Id = //fetch data

        Result = Delete_Data( Mat_Id, Grade_Id, Item_Id, UserId.ToString());

        Bind_GV();
    }

    protected void GV_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Design obj = new Design();
        Label Mat_Id = (Label)GV.Rows[e.RowIndex].FindControl("lblMat_Id");
        Label Grade_Id = //fetch data
        Label Item_Id = //fetch data
        TextBox qty = (TextBox)GV.Rows[e.RowIndex].FindControl("txtEditQty");

        Result = obj.Update_Details(Mat_Id.Text, Grade_Id.Text, Item_Id.Text, qty.Text, UserId.ToString());

        GV.EditIndex = -1;

        Bind_Tender_Quantity_GV();
    }
    
}




Conclusion: 


 In this article I'm trying to explain how to do editing and updating and cancelling edit with simple example. Hope this will help you who are trying to do this..