ASP.NET Grid View Demo With Data Binding and Deleting

About ASP.NET Grid View


In ASP.NET we have a control called Grid View which gives us a tabular format of data representation. Let's say you have a list of users and you want to show them in a web page then in that case Grid View is the best option to show them.

This article is very simple and about the fundamentals of ASP.NET Grid View, There will be a series of articles I will be publishing in the label of ASP.NET Grid View where you can find all possible interactions with the control.

And in this article I will explain the basics of the Grid View, How to bind an ASP.NET Grid View, and how to delete a row from the Grid View.


Grid View Demo For User List
For more details about Grid View here is the Microsoft link GridView Class.


   Download Source Code Here


Let's Create a Grid View and Bind it

Ok, let's take a grid view control in our aspx page. Find the control below and I will explain all the items of it one by one.
<asp:GridView runat="server" ID="grdDemo" AutoGenerateColumns="false" CssClass="table table-bordered table-hover table-striped table-responsive"
     OnRowCommand="grdDemo_RowCommand" DataKeyNames="ID">
     <Columns>
         <asp:TemplateField HeaderText="ID" ItemStyle-Width="10%">
             <ItemTemplate>
                 <asp:Label runat="server" ID="lblID" Text='<%#Eval("ID") %>'></asp:Label>
             </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="First Name" ItemStyle-Width="20%">
             <ItemTemplate>
                 <asp:Label runat="server" ID="lblFirstName" Text='<%#Eval("FirstName") %>'></asp:Label>
             </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="Last Name" ItemStyle-Width="20%">
             <ItemTemplate>
                 <asp:Label runat="server" ID="lblLastName" Text='<%#Eval("LastName") %>'></asp:Label>
             </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="Mobile" ItemStyle-Width="25%">
             <ItemTemplate>
                 <asp:Label runat="server" ID="lbMobile" Text='<%#Eval("Mobile") %>'></asp:Label>
             </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="Email" ItemStyle-Width="25%">
             <ItemTemplate>
                 <asp:Label runat="server" ID="lblEmail" Text='<%#Eval("Email") %>'></asp:Label>
             </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="Action" ItemStyle-Width="25%">
             <ItemTemplate>
                 <asp:LinkButton runat="server" Text="Delete" ID="lbtnDeleteUser" OnClientClick="return confirm('Are you sure you want to delete this user ?');"
                     CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' CommandName="DeleteCommand"> </asp:LinkButton>
             </ItemTemplate>
         </asp:TemplateField>
     </Columns>
 </asp:GridView>
If You look into the above code you will find some attributes those are new to you. Let me give you an idea about the attributes.


AutoGenerateColumns : This attribute has two values true and false. If its true then the gridview will generate columns automatically from the data source.

OnRowCommand : This will fire an event when you define any command inside the grid view like Edit, Update, Delete. In this example I have taken a Delete button in the last Template field which has a command name equals to DeleteCommand, when you click on the button it will fire the OnRowCommand

* If you will give the command name as Delete then it will automatically fire a RowDeleting Event and same as Edit. So avoid giving Delete and Edit in command names.

There are two options to bind columns into the gridview.
  • Bound Fields 
  • Template Fields
Bound fields don't allow you to do much stuffs with them, these are just labels, responsible to show data. But the Template fields allow you to take controls according to you like labels, textboxes, buttons etc inside them.


Inside the Template field you can see I am writing something like Text='<%#Eval("ID") %>' This is responsible to get the data from the DataSource, that you are going to bind with the gridview. The above text will show the ID in a label.
Data dt = new Data();

    /// <summary>
    /// Page_Load
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        BindGrid();
    }

    /// <summary>
    /// Here I am binding the data to the grid view.
    /// </summary>
    private void BindGrid()
    {
        DataTable dtUser = dt.GetUserList();

        grdDemo.DataSource = dtUser;
        grdDemo.DataBind();
    }
    
    /// <summary>
    /// This method is responsible for deleting the row of the grid view.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grdDemo_RowCommand(Object sender, GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "DeleteCommand")
            {                   
                int ID = 0;
                int index = -1;

                // Get the row index
                int.TryParse(Convert.ToString(e.CommandArgument), out index);

                // Get the row object
                GridViewRow gRow = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

                // Get the id of the row 
                Label lblID = (Label)gRow.FindControl("lblID");                    
                int.TryParse(lblID.Text.Trim(), out ID);

                // Now delete user row
                dt.DeleteUser(ID);

                // Now refresh the grid 
                BindGrid();
            }               
        }
        catch (Exception ex)
        {
            lblError.Text = "Some Error Occured in The Background...";
        }
    }
Now we need to bind the Grid view in Page load or you can do where you want to do. So check the above code where I am calling BindGrid  method to bind the grid from Page Load.

And you can see the OnRowCommand method. Check it out how I am getting the row index, which is very important to delete an row. Once you get the row index then you can get the data of the controls by finding them. See the above code for better understanding.

For deletion I am checking the command name in the OnRowCommand and if it matches to the command name I have given in the aspx page then the following code bloc will be executed.


In my demo project I have defined a new class named Data for getting the Data from database. This class has the below 3 methods to get the data, delete the data and to refresh the data.
    public class Data
    {
        // This is the connection string.
        string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["constrng"].ConnectionString;

        /// <summary>
        /// This method deletes the user record form the database.
        /// </summary>
        /// <param name="ID"></param>
        public void DeleteUser(int ID)
        {
            try
            {
                using (var con = new SqlConnection(connectionString))
                {
                    con.Open();

                    SqlCommand cmd = new SqlCommand();
                    SqlDataAdapter SqlDadp = new SqlDataAdapter();

                    cmd = new SqlCommand("[DeleteUser]", con);
                    cmd.Parameters.Add("@ID", SqlDbType.Int);
                    cmd.Parameters["@ID"].Value = ID;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        /// Refresh the user data by making the isDeleted field 0
        /// </summary>
        public void RefreshUserList()
        {
            try
            {
                using (var con = new SqlConnection(connectionString))
                {
                    con.Open();

                    SqlCommand cmd = new SqlCommand();
                    SqlDataAdapter SqlDadp = new SqlDataAdapter();

                    cmd = new SqlCommand("[RefreshUser]", con);

                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// This method gets all the user details form the database.
        /// </summary>
        /// <returns></returns>
        public DataTable GetUserList()
        {
            DataTable dt = new DataTable();

            try
            {
                using (var con = new SqlConnection(connectionString))
                {
                    con.Open();

                    SqlCommand cmd = new SqlCommand();
                    SqlDataAdapter SqlDadp = new SqlDataAdapter();

                    cmd = new SqlCommand("[GetUserList]", con);

                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlDadp.SelectCommand = cmd;
                    SqlDadp.Fill(dt);
                }

                return dt;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
For testing purpose in the attached demo project I have a refresh button there which will refresh the data entered in the data base by making the isDeleted field equals to 0.

 In the demo project I have used a mdf file for data base whose location path has been set in the config file. In order to run this application you need to change the location according to your folder structure. and then try running it.

In my case the path is "E:\OTHERS\Test Projects\GridViewDemo\GridViewDemo\App_Data\User.mdf" in the web config file which you need to change when you try to run this application.


 Happy Coding...

No comments:

Post a Comment