Tuesday, June 11, 2013

GridView basic operations Edit Delete Add New: Asp:Net

The code facilitates simple operation of a GridView as Edit, Delete and Insert.

Default.aspx:

 <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
        <table>
     
        <tr>
        <td>
        <asp:Label ID="Label1" runat="server" Text="Grid View Basic Operations"></asp:Label>
        </td>
        </tr>
        <tr>
        <td style="height:50px">
     
        </td>
        </tr>
        <tr>
        <td>
            <asp:Button ID="btnCreateNew" runat="server" Text="Create New User" OnClick="btnCreateNew_Click" />
     
        </td>
        </tr>
           <tr>
        <td style="height:50px">
     
        </td>
        </tr>
        <tr>
        <td>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
        OnRowCancelingEdit="GridView1_RowCancelingEdit"
       OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"
       OnRowUpdating="GridView1_RowUpdating" OnRowDataBound="GridView1_RowDataBound"
       OnRowCommand="GridView1_RowCommand" DataKeyNames="UserId"   >
     
        <Columns>
        <asp:BoundField DataField="UserId" Visible="false" />
     
        <asp:TemplateField HeaderText="UserName">
        <ItemTemplate>
            <asp:Label ID="lblUserName" runat="server" Text='<%# Bind("UserName") %>'></asp:Label>
        </ItemTemplate>
     
        <EditItemTemplate>
            <asp:TextBox ID="txtUserName" runat="server" Text='<%# Bind("UserName") %>'></asp:TextBox>
     
        </EditItemTemplate>
     
        <FooterTemplate>
         <asp:TextBox ID="txtNewUserName" runat="server" ></asp:TextBox>
        </FooterTemplate>
     
        </asp:TemplateField>
     
        <asp:TemplateField HeaderText="Email Id">
        <ItemTemplate>
            <asp:Label ID="lblEmail" runat="server" Text='<%# Bind("Email") %>'></asp:Label>
        </ItemTemplate>
     
        <EditItemTemplate>
            <asp:TextBox ID="txtEmail" runat="server" Text='<%# Bind("Email") %>'></asp:TextBox>
     
        </EditItemTemplate>
     
        <FooterTemplate>
         <asp:TextBox ID="txtNewEmail" runat="server" ></asp:TextBox>
        </FooterTemplate>
     
        </asp:TemplateField>
     
     
        <asp:TemplateField HeaderText="Gender">
        <ItemTemplate>
            <asp:Label ID="lblGender" runat="server" Text='<%# Bind("Gender") %>'></asp:Label>
        </ItemTemplate>
     
        <EditItemTemplate>
           <asp:RadioButtonList runat="server" ID="rblGender" RepeatDirection="Horizontal">
           <asp:ListItem Text="Male" Value="Male" />
           <asp:ListItem Text="Female" Value="Female" />
           </asp:RadioButtonList>
     
        </EditItemTemplate>
     
        <FooterTemplate>
     
         <asp:RadioButtonList runat="server" ID="rblNewGender" RepeatDirection="Horizontal">
           <asp:ListItem Text="Male" Value="Male" />
           <asp:ListItem Text="Female" Value="Female" />
          </asp:RadioButtonList>
       
        </FooterTemplate>
     
        </asp:TemplateField>
     
         <asp:TemplateField HeaderText="Department">
        <ItemTemplate>
            <asp:Label ID="lblDepartment" runat="server" Text='<%# Bind("Department") %>'></asp:Label>
        </ItemTemplate>
     
        <EditItemTemplate>
            <asp:TextBox ID="txtDepartment" runat="server" Text='<%# Bind("Department") %>'></asp:TextBox>
     
        </EditItemTemplate>
     
        <FooterTemplate>
     
          <asp:TextBox ID="txtNewDepartment" runat="server"></asp:TextBox>
        </FooterTemplate>
     
        </asp:TemplateField>
     
        <asp:TemplateField HeaderText="Location">
        <ItemTemplate>
            <asp:Label ID="lblLocation" runat="server" Text='<%# Bind("Location") %>'></asp:Label>
        </ItemTemplate>
     
        <EditItemTemplate>
            <asp:TextBox ID="txtLocation" runat="server" Text='<%# Bind("Location") %>'></asp:TextBox>
     
        </EditItemTemplate>
     
        <FooterTemplate>
     
          <asp:TextBox ID="txtNewLocation" runat="server"></asp:TextBox>
        </FooterTemplate>
     
        </asp:TemplateField>
     
        <asp:TemplateField>
        <ItemTemplate>
         <asp:LinkButton ID="lbtnEdit" Text="Edit" CommandName="Edit"  runat="server" />
          <asp:LinkButton ID="lbtnDelete" Text="Delete" CommandName="Delete"  runat="server"
           OnClientClick= "return confirm('Are you sure you want to delete this user?');" />
        </ItemTemplate>
     
        <EditItemTemplate>
         <asp:LinkButton ID="lbtnUpdate" Text="Update" CommandName="Update"  runat="server" />
          <asp:LinkButton ID="lbtnCancel" Text="Cancel" CommandName="Cancel"  runat="server" />
        </EditItemTemplate>
     
        <FooterTemplate>
        <asp:LinkButton ID="lbtnAddNew" Text="Add" CommandName="Insert"  runat="server" />
       </FooterTemplate>
     
     
        </asp:TemplateField>
     
        </Columns>
     
        </asp:GridView>
        </td>
        </tr>
        </table>
     
             
        </ContentTemplate>
        </asp:UpdatePanel>
     
   
    </div>
I have bind the GridView with a List object here.

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GridProject
{
    public partial class _Default : System.Web.UI.Page
    {
        private List<UserDetails> users;
        protected void Page_Load(object sender, EventArgs e)
        {
            users = new List<UserDetails>();
            users = GetUserList();
            if (!IsPostBack)
            {
                BindGridView(users);
             

            }

        }

        private void BindGridView(List<UserDetails> users)
        {
            GridView1.DataSource = users;
            GridView1.DataBind();
        }

        protected void btnCreateNew_Click(object sender, EventArgs e)
        {
            GridView1.ShowFooter = true;
            BindGridView(users);
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            BindGridView(users);
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int userId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
            TextBox txtUserName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUserName");
            TextBox txtEmail = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmail");
            TextBox txtDepartment = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtDepartment");
            TextBox txtLocation = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtLocation");
            RadioButtonList rblGender = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("rblGender");

            users.RemoveAll(u => u.UserId == userId);
            users.Add(new UserDetails { UserId = userId, UserName = txtUserName.Text, Email = txtEmail.Text, Gender = rblGender.SelectedValue, Department = txtDepartment.Text, Location = txtLocation.Text });
            users = users.OrderBy(u => u.UserId).Distinct().ToList<UserDetails>();
            GridView1.EditIndex = -1;
            BindGridView(users);
         
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Insert")
            {
                TextBox txtUserName = (TextBox)GridView1.FooterRow.FindControl("txtNewUserName");
                TextBox txtEmail = (TextBox)GridView1.FooterRow.FindControl("txtNewEmail");
                TextBox txtDepartment = (TextBox)GridView1.FooterRow.FindControl("txtNewDepartment");
                TextBox txtLocation = (TextBox)GridView1.FooterRow.FindControl("txtNewLocation");
                RadioButtonList rblGender = (RadioButtonList)GridView1.FooterRow.FindControl("rblNewGender");
                int newUserId = users.Max(u => u.UserId)+1;
                users.Add(new UserDetails { UserId = newUserId, UserName = txtUserName.Text, Email = txtEmail.Text, Gender = rblGender.SelectedValue, Department = txtDepartment.Text, Location = txtLocation.Text });
                GridView1.ShowFooter = false;
                BindGridView(users);
            }
         
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int userId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
            users.RemoveAll(u => u.UserId == userId);
            BindGridView(users);
         
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            BindGridView(users);
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.RowState==DataControlRowState.Edit || e.Row.RowState == (DataControlRowState.Edit|DataControlRowState.Alternate))
                {
                    RadioButtonList rblGender = (RadioButtonList)e.Row.FindControl("rblGender");
                    rblGender.SelectedValue = ((UserDetails)e.Row.DataItem).Gender;
                }
            }
        }

        //Creating a Dummy List and returning the same
        private List<UserDetails> GetUserList()
        {
            users.Add(new UserDetails { UserId = 1, UserName = "Peter Henry", Email = "peter@abc.com", Gender = "Male", Department = "IT", Location = "London" });
            users.Add(new UserDetails { UserId = 2, UserName = "Judy Kelsey", Email = "judy@abc.com", Gender = "Female", Department = "Finance", Location = "Munich" });
            users.Add(new UserDetails { UserId = 3, UserName = "Sreeram", Email = "sree@abc.com", Gender = "Male", Department = "IT", Location = "India" });
            users.Add(new UserDetails { UserId = 4, UserName = "Ann Andersson", Email = "ann@abc.com", Gender = "Female", Department = "SAP", Location = "US" });
            users.Add(new UserDetails { UserId = 5, UserName = "Dan Pery", Email = "dan@abc.com", Gender = "Male", Department = "SAP", Location = "Singapore" });
            return users;

        }
    }



    public class UserDetails
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string Email { get; set; }
        public string Gender { get; set; }
        public string Department { get; set; }
        public string Location { get; set; }
    }
}


The output of the page is




No comments:

Post a Comment