Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView in asp.net C#

save, edit, update, delete, paging example in gridview
Click on Image to enlarge
IntroductionIn this article I am going to explain How to perform Bind, Insert/Save, Edit, Update, Cancel, Delete, Paging in GridView in asp.net using C# language.
    Basically you will learn the following through this example: 
  • How to Save/Insert and update data in Sql Server Database from asp.net web application?
  • How to Bind Data from Sql Server to GridView Data Control?
  • How to perform Edit, Update and Delete operation in GridView?
  • How to Fill Day, Month and Year in DropDownList and set current date as selected?
  • How to find controls like TextBox and DropDownList placed inside GridView and get their values?
  • How to implement paging in GridView?


Implementation: Let's create an example web application to see it in action.
Bind,save, edit, update, delete, paging example in gridview
Click on image  to enlarge
  • First of all create the Database in Sql Server and Name it "Emp_DB" or whatever you want. Create a Table having columns as shown in figure and  name it "Emp_Tb" .
Note: Emp_Id_Pk column is set to Primary key and Identity specification is set to yes with Identity increment and Identity seed equal to 1.
  • In the Web.config file create the connection string as:
<connectionStrings>
                                <add name="conStr" connectionString="Data Source=LocalServer;Initial Catalog=Emp_DB;Integrated Security=True"/>
                </connectionStrings>

Note: Replace the Data Source and the Initial catalog as per your application.
  • Create a folder in the root directory and name it "Images". Search edit and delete .png icon image from the google search and add in the "Images" folder.
  •   Now In the Design page(.aspx) design  the  web page as:
Note: I have also implemented the asp.net validations on the Employee Name, Address and the Salary fields.

<fieldset style="width:545px;">
    <legend style="font-size:20px; color:Green;">Save, Edit, Update, Delete, Paging example in
        Gridview</legend>   
        <table>
            <tr>
                <td>
                    Employee Name</td>
                <td>
                    <asp:TextBox ID="txtEmployeeName" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvEmpName" runat="server"
                        ErrorMessage="Please enter employee name"
                        ControlToValidate="txtEmployeeName" Display="Dynamic" ForeColor="Red"
                        SetFocusOnError="True"></asp:RequiredFieldValidator>
                </td>
            </tr>           
            <tr>
                <td>
                    Address</td>
                <td>
                    <asp:TextBox ID="txtAddress" runat="server" TextMode="MultiLine" Height="59px"
                        Width="267px"></asp:TextBox><asp:RequiredFieldValidator ID="rfvAddress" runat="server"
                        ErrorMessage="Please enter Address"
                        ControlToValidate="txtAddress" Display="Dynamic" ForeColor="Red"
                        SetFocusOnError="True"></asp:RequiredFieldValidator>
                </td>
            </tr>           
            <tr>
                <td>
                    DOJ</td>
                <td>
                    <asp:DropDownList ID="ddlYear" runat="server"  ToolTip="Select Year"
                        onselectedindexchanged="ddlYear_SelectedIndexChanged">
                    </asp:DropDownList>
                    <asp:DropDownList ID="ddlMonth" runat="server" ToolTip="Select Month"
                        onselectedindexchanged="ddlMonth_SelectedIndexChanged">
                    </asp:DropDownList>
                    <asp:DropDownList ID="ddlDay" runat="server" ToolTip="Select Day">
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>
                    Salary</td>
                <td>
                    <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvSal" runat="server"
                        ErrorMessage="Please enter salary" ControlToValidate="txtSalary"
                        Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
                </td>
            </tr>      
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
                    <asp:Button ID="btnReset" runat="server" Text="Reset" CausesValidation="false"
                        onclick="btnReset_Click" />
                </td>
            </tr>           
            </table>   

        <asp:GridView ID="grdEmp" runat="server"
            DataKeyNames="Emp_Id_Pk"  CssClass="rowHover" RowStyle-CssClass="rowHover"
            AutoGenerateColumns="False" AllowPaging="True" onpageindexchanging="grdEmp_PageIndexChanging"
            PageSize="4" onrowcancelingedit="grdEmp_RowCancelingEdit"
            onrowdeleting="grdEmp_RowDeleting" onrowediting="grdEmp_RowEditing"
            onrowupdating="grdEmp_RowUpdating" onrowdatabound="grdEmp_RowDataBound"
             CellPadding="4" ForeColor="#333333" GridLines="None">          
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />          
         <Columns>          
                <asp:TemplateField HeaderText="Emp Name" HeaderStyle-HorizontalAlign="Center">
            <ItemTemplate>
                 <%#Eval("EmpName")%>
            </ItemTemplate>
            <EditItemTemplate>
                 <asp:TextBox ID="txtEmpName" runat="server" Text='<%#Eval("EmpName") %>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvEmpName" runat="server" ErrorMessage="*" ForeColor="red" ControlToValidate="txtEmpName" Display="Dynamic" SetFocusOnError="True"></asp:RequiredFieldValidator>
             </EditItemTemplate>
              <HeaderStyle HorizontalAlign="Center" />            
         </asp:TemplateField>       
        <asp:TemplateField HeaderText="Address" HeaderStyle-HorizontalAlign="Center">
            <ItemTemplate>
                 <%#Eval("Address")%>
            </ItemTemplate>
            <EditItemTemplate>
                 <asp:TextBox ID="txtEditAddress" runat="server" Text='<%#Eval("Address") %>'  TextMode="MultiLine"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvAddress" runat="server" ErrorMessage="*" ForeColor="red" ControlToValidate="txtEditAddress" Display="Dynamic" SetFocusOnError="True"></asp:RequiredFieldValidator>
             </EditItemTemplate>
              <HeaderStyle HorizontalAlign="Center" />            
         </asp:TemplateField>
        <asp:TemplateField HeaderText="DOJ" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="180px">
         <ItemTemplate>
        <%#Eval("DOJ""{0:dd/MM/yyyy}")%>   
         </ItemTemplate>
         <EditItemTemplate>
               <asp:DropDownList ID="ddlEditDay" runat="server" ToolTip="Select Day">
              </asp:DropDownList>
              <asp:DropDownList ID="ddlEditMonth" runat="server" ToolTip="Select Month">
                    </asp:DropDownList>
              <asp:DropDownList ID="ddlEditYear" runat="server" ToolTip="Select Year">
                    </asp:DropDownList>
         </EditItemTemplate>        
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Center" Width="180px" />        
         </asp:TemplateField>
           <asp:TemplateField HeaderText="Salary" HeaderStyle-HorizontalAlign="Center">
            <ItemTemplate>
                 <%#Eval("Salary")%>
            </ItemTemplate>
            <EditItemTemplate>
                 <asp:TextBox ID="txtSal" runat="server" Text='<%#Eval("Salary") %>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvSal" runat="server" ErrorMessage="*" ForeColor="red" ControlToValidate="txtSal" Display="Dynamic" SetFocusOnError="True"></asp:RequiredFieldValidator>
             </EditItemTemplate>
              <HeaderStyle HorizontalAlign="Center" />             
         </asp:TemplateField>
                   <asp:TemplateField HeaderText="Edit"  HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>             
                <asp:ImageButton ID="imgEdit" runat="server" CommandName="Edit"  ImageUrl="~/Images/Edit.png" ToolTip="Edit" CausesValidation="false"/>
            </ItemTemplate>
            <EditItemTemplate>
                 <asp:LinkButton ID="lkUpdate" runat="server" Text="Update" CommandName="Update" ToolTip="Update" CausesValidation="false"></asp:LinkButton>
                 <asp:LinkButton ID="lkCancel" runat="server"  Text="Cancel" CommandName="Cancel" ToolTip="Cancel" CausesValidation="false"></asp:LinkButton>               
             </EditItemTemplate>
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Center" />
         </asp:TemplateField>
         <asp:TemplateField HeaderText="Delete"  HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                 <asp:ImageButton ID="imgDelete" runat="server" CommandName="Delete"  ImageUrl="~/Images/Delete.png" OnClientClick="return confirm('Are you sure you want to delete selected record ?')" ToolTip="Delete" CausesValidation="false"/>
            </ItemTemplate>           
             <HeaderStyle HorizontalAlign="Center" />
             <ItemStyle HorizontalAlign="Center" />
         </asp:TemplateField>   
                  </Columns>        
             <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle CssClass="rowHover" BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />       
         </asp:GridView>    
         </fieldset>

C#.Net Code to Bind, Save, Edit, Update, Cancel, Delete, Paging example  in GridView
  • In the Code behind file (.aspx.cs) write the code as:
#region "namespaces"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
#endregion

public partial class _Default : System.Web.UI.Page
    //Creating Connection object and getting connection string
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

    #region "page Load"
    protected void Page_Load(object sender, EventArgs e)
    {
        //Check and Open Database connection
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        if (!Page.IsPostBack)
        {
            //Bind gridview existing records
            bindGridView();

            //DOJ Field
            //Fill Years with current year selected
            for (int i = 2013; i >= 1980; i--)
            {
                ddlYear.Items.Add(i.ToString());
            }
            ddlYear.Items.FindByValue(System.DateTime.Now.Year.ToString()).Selected = true;  //set current year as selected

            //Fill Months with current month selected
            for (int i = 1; i <= 12; i++)
            {
                ddlMonth.Items.Add(i.ToString());
            }
            ddlMonth.Items.FindByValue(System.DateTime.Now.Month.ToString()).Selected = true// Set current month as selected

            //Fill days based on selected month
            FillDays();
        }
    }
    #endregion

    #region "Save employee record"
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string doj = string.Empty;
        //Joining selected Day, month and year to create Date of Joining
       doj = Convert.ToString(ddlDay.SelectedValue + "/" + ddlMonth.SelectedValue + "/" + ddlYear.SelectedValue);
        try
        {
            SqlCommand cmd = new SqlCommand("Insert into Emp_Tb(EmpName,Address,DOJ,Salary) values (@EmpName,@Address,@Doj,@Salary)", con);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@EmpName"SqlDbType.VarChar, 100).Value = txtEmployeeName.Text.Trim();        
            cmd.Parameters.Add("@Address"SqlDbType.VarChar, 500).Value =  txtAddress.Text.Trim();  
            cmd.Parameters.Add("@Doj"SqlDbType.VarChar, 50).Value = doj;
            cmd.Parameters.Add("@Salary"SqlDbType.Int).Value = txtSalary.Text.Trim();          
            cmd.ExecuteNonQuery();
           //Clear all controls after saving the record
            Clear_Controls();
            //Bind gridview after saving the record
            bindGridView();
        }
        catch (Exception ex)
        { 
            // Show error occurred in message box using JavaScript
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + ex.Message.ToString() + "');"true);
        }
        finally
        {
            doj = string.Empty;
            //close the database connection
            con.Close();
        }
    }
    #endregion

    #region "Bind gridview with data"
    public void bindGridView()
    {     
            try
            {
                SqlCommand cmd = new SqlCommand("select * from Emp_Tb", con);
                SqlDataAdapter adp = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adp.Fill(ds);
              
                if (ds.Tables[0].Rows.Count > 0)
                {                  
                    grdEmp.DataSource = ds;
                    grdEmp.DataBind();
                }
                else
                {  
                    //Bind Empty grdview with Columns names in Header and "No employee record found" message if no records are found in the database
                    BindEmptyGridWithHeader(grdEmp, ds);
                }
            }
            catch (Exception ex)
            {              
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + ex.Message.ToString() + "');"true);
            }
            finally
            {               
                con.Close();
            }    
           }   
    #endregion
   
    #region "paging in gridview"
    protected void grdEmp_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdEmp.PageIndex = e.NewPageIndex;
        //Call bind gridview function
        bindGridView();
    }
    #endregion

    #region "Cancel code in gridview"
    protected void grdEmp_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grdEmp.EditIndex = -1;
        bindGridView();
    }
    #endregion

    #region "Deletion in gridview"
    protected void grdEmp_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            int empId = Convert.ToInt32(grdEmp.DataKeys[e.RowIndex].Value);
            SqlCommand cmd = new SqlCommand("delete from Emp_Tb where Emp_Id_Pk= @EmpId", con);
            cmd.Parameters.Add("@EmpId"SqlDbType.Int).Value = empId;
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            grdEmp.EditIndex = -1;
            bindGridView();
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('"+ ex.Message.ToString() +"');"true);
        }
        finally
        {
            con.Close();
        }
    }
    #endregion

    #region "updation in gridview"
    protected void grdEmp_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {    
        string empName = string.Empty;
        string address = string.Empty;
        string dojUpdated = string.Empty;     
        try
        {
            // Finding dropdownlist inside gridview and getting updated value
            DropDownList ddlEditDojYear = (DropDownList)(grdEmp.Rows[e.RowIndex].FindControl("ddlEditYear"));
            DropDownList ddlEditDojMonth = (DropDownList)(grdEmp.Rows[e.RowIndex].FindControl("ddlEditMonth"));
            DropDownList ddlEditDojDay = (DropDownList)(grdEmp.Rows[e.RowIndex].FindControl("ddlEditDay"));

            // creating Updated DOJ field
            dojUpdated = Convert.ToString(ddlEditDojDay.SelectedValue + "/" + ddlEditDojMonth.SelectedValue + "/" + ddlEditDojYear.SelectedValue);
           
            //Read Emp_id_Pk from DataKeyNames
            int empId = Convert.ToInt32(grdEmp.DataKeys[e.RowIndex].Value);
            //Finding TextBox inside gridview and getting updated value
            empName = ((TextBox)(grdEmp.Rows[e.RowIndex].FindControl("txtEmpName"))).Text.Trim();
            address = ((TextBox)(grdEmp.Rows[e.RowIndex].FindControl("txtEditAddress"))).Text.Trim();
            int sal = Convert.ToInt32(((TextBox)(grdEmp.Rows[e.RowIndex].FindControl("txtSal"))).Text.Trim());

            SqlCommand cmd = new SqlCommand("update Emp_Tb set EmpName=@EmpName,Address=@Address,DOJ=@Doj,Salary=@Salary where Emp_Id_Pk=@EmpId", con);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@EmpId"SqlDbType.Int).Value = empId;
            cmd.Parameters.Add("@EmpName"SqlDbType.VarChar, 50).Value = empName;
            cmd.Parameters.Add("@Address"SqlDbType.VarChar, 50).Value = address;        
            cmd.Parameters.Add("@Doj"SqlDbType.VarChar, 50).Value = dojUpdated;
            cmd.Parameters.Add("@Salary"SqlDbType.BigInt).Value = sal;          
            cmd.ExecuteNonQuery();
            grdEmp.EditIndex = -1;
            bindGridView();
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + ex.Message.ToString() + "');"true);
        }
        finally
        {         
            empName = string.Empty;
            address = string.Empty;
            dojUpdated = string.Empty;
            con.Close();
        }
    }
    #endregion

    #region "Editing in gridview"
    protected void grdEmp_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grdEmp.EditIndex = e.NewEditIndex;
        bindGridView();
    }
    #endregion

    #region "Bind Empty Gridview with header"
    public void BindEmptyGridWithHeader(GridView gridView, DataSet ds)
    {
        try
        {
            if (ds.Tables[0].Rows.Count == 0)
            {
                //Add a blank row to the dataset
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                //Bind the DataSet to the GridView
                gridView.DataSource = ds;
                gridView.DataBind();
                //Get the number of columns to know what the Column Span should be
                int columnCount = gridView.Rows[0].Cells.Count;
                //Call the clear method to clear out any controls that you use in the columns.
                gridView.Rows[0].Cells.Clear();
                gridView.Rows[0].Cells.Add(new TableCell());
                gridView.Rows[0].Cells[0].ColumnSpan = columnCount;
                gridView.Rows[0].Cells[0].Text = "<font color=Red><b><center>No employee record Found !</center></b></font>";
            }
        }
        catch (Exception ex)
        {
            //Do your exception handling here
        }
    }
    #endregion   
   
    #region "Grid RowDataBound Event"
    protected void grdEmp_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        string day = string.Empty;
        string month = string.Empty;
        string year = string.Empty;     
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow && grdEmp.EditIndex == e.Row.RowIndex)
            {
                //Read Emp_Id_Pk from DataKeyNames
                int empId = Convert.ToInt32(grdEmp.DataKeys[e.Row.RowIndex].Value);
                SqlDataAdapter adp1 = new SqlDataAdapter("Select * from Emp_Tb where Emp_Id_Pk=@EmpId", con);
                adp1.SelectCommand.CommandType = CommandType.Text;
                adp1.SelectCommand.Parameters.Add("@EmpId"SqlDbType.Int).Value = empId;
                DataTable dtEdit = new DataTable();
                adp1.Fill(dtEdit);
                string getDoj = dtEdit.Rows[0]["DOJ"].ToString();

                //Splitting the DOJ field into day, month and year
                string[]  strDoj = getDoj.Split('/');
                 day = strDoj[0];
                 month = strDoj[1];
                 year = strDoj[2];

                DropDownList ddlEditDojYear = (DropDownList)(e.Row.FindControl("ddlEditYear"));
                DropDownList ddlEditDojMonth = (DropDownList)(e.Row.FindControl("ddlEditMonth"));
                DropDownList ddlEditDojDay = (DropDownList)(e.Row.FindControl("ddlEditDay"));
                //Fill Years
                for (int i = 2013; i >= 1980; i--)
                {
                    ddlEditDojYear.Items.Add(i.ToString());
                }             
                 ddlEditDojYear.SelectedValue = year;

                //Fill Months
                for (int i = 1; i <= 12; i++)
                {
                    ddlEditDojMonth.Items.Add(i.ToString());
                }
                ddlEditDojMonth.SelectedValue = month;               
               
                //Fill days
                FillDaysInsideGrid(ddlEditDojDay, ddlEditDojYear, ddlEditDojMonth, day);
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + ex.Message.ToString() + "');"true);
        }
        finally
        {
             day = string.Empty;
             month = string.Empty;
             year = string.Empty;           
        }      
    }
    #endregion          
   
    #region "DOJ"
    protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillDays();
    }
    protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillDays();
    }
    public void FillDays()
    {
        if (!Page.IsPostBack)
        {
            ddlDay.Items.Clear();
        }
        //getting number of days in selected month & year
        int noofdays = DateTime.DaysInMonth(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt32(ddlMonth.SelectedValue));

        //Fill days
        for (int i = 1; i <= noofdays; i++)
        {
            ddlDay.Items.Add(i.ToString());
        }
        if (!Page.IsPostBack)
        {
            ddlDay.Items.FindByValue(System.DateTime.Now.Day.ToString()).Selected = true;// Set current date as selected
        }
    }
    #endregion

    #region "Fill Days Inside GridView"
    public void FillDaysInsideGrid(DropDownList ddlEditDojDay, DropDownList ddlEditDojYear, DropDownList ddlEditDojMonth, string day)
    {
        ddlEditDojDay.Items.Clear();
        //getting number of days in selected month & year
        int noofdays = DateTime.DaysInMonth(Convert.ToInt32(ddlEditDojYear.SelectedValue), Convert.ToInt32(ddlEditDojMonth.SelectedValue));

        //Fill days
        for (int i = 1; i <= noofdays; i++)
        {
            ddlEditDojDay.Items.Add(i.ToString());
        }
                ddlEditDojDay.SelectedValue = day;
    }
    #endregion

    #region "Clear & reset all controls"
           
    protected void btnReset_Click(object sender, EventArgs e)
    {
        Clear_Controls();
    }
    private void Clear_Controls()
    {
        txtEmployeeName.Text = string.Empty;
        txtSalary.Text = string.Empty;
        txtEmployeeName.Focus();
        txtAddress.Text = string.Empty;
        txtEmployeeName.Focus();

        //Reset DOJ Field
        //Fill Years with current year selected
        ddlYear.Items.Clear();
        for (int i = 2013; i >= 1980; i--)
        {
            ddlYear.Items.Add(i.ToString());
        }
        ddlYear.Items.FindByValue(System.DateTime.Now.Year.ToString()).Selected = true;  //set current year as selected

        //Fill Months with current month selected
        ddlMonth.Items.Clear();
        for (int i = 1; i <= 12; i++)
        {
            ddlMonth.Items.Add(i.ToString());
        }
        ddlMonth.Items.FindByValue(System.DateTime.Now.Month.ToString()).Selected = true// Set current month as selected

        //Fill days according to current month  
        ddlDay.Items.Clear();

        //Getting number of days in selected month & year
        int noofdays = DateTime.DaysInMonth(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt32(ddlMonth.SelectedValue));

        //Fill days
        for (int i = 1; i <= noofdays; i++)
        {
            ddlDay.Items.Add(i.ToString());
        }
        ddlDay.Items.FindByValue(System.DateTime.Now.Day.ToString()).Selected = true;// Set current date as selected      
    }
    #endregion
}

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."
Previous
Next Post »

67 comments

Click here for comments
Anonymous
August 21, 2013 ×

*****

Reply
avatar
admin
August 22, 2013 ×

thanks for giving this article 5 star..

Reply
avatar
admin
Anonymous
August 23, 2013 ×

*****

Reply
avatar
admin
August 23, 2013 ×

thanks..stay tuned and stay connected for more useful updates..

Reply
avatar
admin
September 05, 2013 ×

Hiiiii Lalit Raghuvanshi,am rama i want to Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView in asp.net with vb.net,plz can you send my mailid,rcdas2012@gmail.com

Thanks in advance

Reply
avatar
admin
September 05, 2013 ×

Hello Ram Das.
read the same article in VB.net on:
How to Bind,Insert,Edit,Update,Delete in GridView in asp.net VB.Net
http://www.webcodeexpert.com/2013/07/how-to-bindinserteditupdatedelete-in.html

Reply
avatar
admin
Anonymous
September 09, 2013 ×

sir i m sameer roy
my database insertion and edit/ delete button can't work in this tutorial , database can't affacted

Reply
avatar
admin
September 09, 2013 ×

Hello sameer. the code in this article is completely working. I suggest you to read the article thoroughly and follow each step and recheck your code. If still you face the problems, let me know. I will help your sort out the problem.

Reply
avatar
admin
September 12, 2013 ×

Thanks Nagendra Babu for appreciating my article..stay tuned and stay connected for more useful updates.

Reply
avatar
admin
September 15, 2013 ×

sir how we use multiple gridvied

Reply
avatar
admin
September 16, 2013 ×

Thanks for appreciating my post..keep reading

Reply
avatar
admin
September 16, 2013 ×

Soon i will post the article related to nested gridview i.e. gridview inside gridview..so stay tuned and stay connected..

Reply
avatar
admin
September 16, 2013 ×

Awesome man.. i was waiting for this one... you saved me..Thnks a lot...god bless you

Reply
avatar
admin
September 16, 2013 ×

Thanks for the appreciation Vikas..stay connected for more technical updates like this..

Reply
avatar
admin
September 17, 2013 ×

hello sir..i want the code for filling up the textbox in one page and tht filled detail showing in other page textbox automatically... for example..
suppose der are two page "first.aspx" and "second.aspx" i've one "textbox" of emailid in "first.aspx" ... if i fill the detail like "abc@abc.com' in tht emailid textbox.. tht "abc@abc.com" should come automatically in "second.aspx" emailid textbox... if you can..plz help me with dis code...else it's ok.. your site already helped me alot... Thank You :)

Reply
avatar
admin
Anonymous
September 17, 2013 ×

very nice ..

Reply
avatar
admin
September 17, 2013 ×

Thanks for appreciating my site..keep reading :)

Reply
avatar
admin
September 18, 2013 ×

Hi Lalit this is a very good example but I am getting an error

Type 'System.Web.UI.WebControls.GridView' does not have a public property named 'TemplateField'.Type 'System.Web.UI.WebControls.GridView' does not have a public property named 'TemplateField'.

i have added the following
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.DataVisualization.Charting;

still i am getting that error pls help me with this

Reply
avatar
admin
September 18, 2013 ×

Hello Ashok..I think you are missing # in the tag e.g.<%#Eval("EmpName")%>. Please check all tags and let me know..

Reply
avatar
admin
September 18, 2013 ×

Hello Vikas shukla..you can use query string for this purpose..pass the value of the email textbox from first.aspx to the second.aspx via querystring and then read the value from the querystring and set to the email textbox of second.aspx..I hope it will help you..

Reply
avatar
admin
September 18, 2013 ×

Thanks sir I got my mistake

Reply
avatar
admin
September 18, 2013 ×

please share how you solved your problem so that other reader don't face the same problem..

Reply
avatar
admin
September 19, 2013 ×

Hi Lalit
Sorry for late reply
I forgot the service call to edit according to the grid that's why I was getting that error.

But now I am getting the problem that my rows are not going in edit mode can you suggest why this is happening.

Reply
avatar
admin
September 19, 2013 ×

Hi ashok..i suggest you to read the article thoroughly and try once again..if still you face the problems then let me know..

Reply
avatar
admin
Anonymous
September 20, 2013 ×

thank u.

Reply
avatar
admin
Anonymous
September 20, 2013 ×

Hi sir this is a very good example but I am getting an error


In .cs file textbox IDs are not recognizing.

Error:
The name 'ddlYear' does not exist in the current

What is the Problem??????

Reply
avatar
admin
September 20, 2013 ×

Hi,I suggest you to recheck all of your code thoroughly..if still you face errors..please let me know..

Reply
avatar
admin
September 20, 2013 ×

your welcome..keep reading :)

Reply
avatar
admin
Anonymous
September 20, 2013 ×

Hi sir
For all the ID's getting same type of error

Error:
The name 'ddlYear' does not exist in the current context.
The name 'txtSalary' does not exist in the current context.
The name 'txtSal' does not exist in the current context.
The name '...' does not exist in the current context.



In .cs file ID's are not recognizing....


Plz help....

Reply
avatar
admin
September 21, 2013 ×

thank u very much sir ....it is very good article.....and what a presentation !...i just love it.....

Reply
avatar
admin
September 21, 2013 ×

thanks for the appreciation Gaju Mundkar..keep reading. :)

Reply
avatar
admin
September 21, 2013 ×

this article is completely working..send your code to my email id lalit24rocks@gmail.com and i will check and help you to sort out the problem you are facing..

Reply
avatar
admin
September 22, 2013 ×

thnk u sir!!gr8 work... but sir m having a error in update n delete!! it says "object cannot be cast from DBNull to other types!! plzz help

Reply
avatar
admin
September 23, 2013 ×

thnxx gt d output!!

Reply
avatar
admin
September 23, 2013 ×

your welcome niraj patel..keep reading :)

Reply
avatar
admin
Anonymous
September 23, 2013 ×

sir how to open upload file without download?i want that click on file and open it.

Reply
avatar
admin
September 23, 2013 ×

Hello..i will upload the article as per your requirement as soon as possible..so keep reading for more updates..:)

Reply
avatar
admin
September 25, 2013 ×

nice one Lalit ji

Reply
avatar
admin
September 25, 2013 ×

Nice one lalit ji

Reply
avatar
admin
September 25, 2013 ×

Thanks Mr. Dinesh Behera for appreciating..keep reading

Reply
avatar
admin
September 26, 2013 ×

Hi Sir . your website has helped me a lot . could you please help me to rectify this error: Server Error --------------------------------------------------------------------------------
Both DataSource and DataSourceID are defined on 'grdEmp'. Remove one definition.

Reply
avatar
admin
Anonymous
September 26, 2013 ×

sir i have a problem in delete
Format of the initialization string does not conform to specification starting at index 0.
give me any solution

Reply
avatar
admin
September 26, 2013 ×

Hello kamal...I think you try to bind data to gridview using sqldatasource from design side as well as using c# code from code behind side..

You need to chose one way to bind the grid
if binding using code behind i.e using code then remove the datasourceid property from grid view

Reply
avatar
admin
September 27, 2013 ×

Thankyou you for your help i have removed the sqldatasource from the property of grid view and now it is working .

Their is another problem that when i insert a data from asp.net page to sql server . The grid view does not get updated i have to refresh the page thern the inserted date gets displayed on the grid view.

Could you please help me as when i click the insert button it should get displayed directly in the grid view without refreshing the page.

Reply
avatar
admin
September 27, 2013 ×

Hello Kamal..i am glad your problem is solved...i think you are skipping the bindGridView() function in the save button click event that will be called after saving the record..please check and let me know..

Reply
avatar
admin
September 27, 2013 ×

Hi..i think your are skipping something in your code...so please recheck and try once more..if still you face error then let me know..i will help you in resolving that..

Reply
avatar
admin
September 28, 2013 ×

Once again thankyou . I was missing the calling function of bindGridView() .
Now it is working perfectly. Your website has really helped me alot . Thanks you your help.

Reply
avatar
admin
September 28, 2013 ×

your welcome kamal..keep reading for more useful stuff :)

Reply
avatar
admin
Anonymous
October 04, 2013 ×

i m manoj kumar thx lalit

Reply
avatar
admin
Anonymous
October 16, 2013 ×

hi sir.want ask u something..how can i edit another form? which is when i click edit from the gridview and it will go to my edit form?

Reply
avatar
admin
October 16, 2013 ×

Your welcome manoj..keep reading :)

Reply
avatar
admin
October 16, 2013 ×

Hello..Pass the id via querystring to another form and on that form based on the id fetch the records from the database and fill in textbox controls to edit..hope you got the point..

Reply
avatar
admin
Anonymous
October 17, 2013 ×

hi..sorry sir i dont get in.plez give me some example.hope u can help me

Reply
avatar
admin
October 18, 2013 ×

grt work i follow ur blog bookmarked

Reply
avatar
admin
October 18, 2013 ×

Thanks Bhaumik for appreciating my work..stay connected for more useful updates like this..:)

Delete

Reply
avatar
admin
October 18, 2013 ×

Hello..I will create an article as per your requirement and publish very soon..so stay connected for more updates..

Reply
avatar
admin
Anonymous
October 28, 2013 ×

can u plz help me ..... I want to make report of accounting..... so i want to make query through which i want to pick data by previous date....????
thanks in advance.

Reply
avatar
admin
Anonymous
December 11, 2013 ×

Hi Sir,
How to create MDL operation manually in GridView. send me all source and steps.

Reply
avatar
admin
December 20, 2013 ×

Thanks Kadir for your appreciation..keep reading for more useful updates like this..:)

Reply
avatar
admin
Anonymous
January 14, 2014 ×

Hello Sir ,
may i get this error Please help me :

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 38: ddlYear.Items.Add(i.ToString());
Line 39: }
Line 40: ddlYear.Items.FindByValue(System.DateTime.Now.Year.ToString()).Selected = true; //set current year as selected
Line 41:
Line 42: //Fill Months with current month selected

Reply
avatar
admin
January 14, 2014 ×

Hi, i suggest you to recheck the article thoroughly and try once again..if still you face issue then let me know.i will help you in sort out your issue..

Reply
avatar
admin
February 05, 2014 ×

Hi, i am getting an error . in this section :
for (int i = 2013; i >= 1980; i--)
{

ddlYear.Items.Add(i.ToString());

}

ddlYear.Items.FindByValue(System.DateTime.Now.Year.ToString()).Selected = true; // in this line it gives an error ---- Object reference not set to an instance of an object.

could you please try to rectify this error
Thankyou.

Reply
avatar
admin
February 08, 2014 ×

Hi, i suggest you to recheck your code thoroughlly..if still you face error then let me know..i will help you to sort out your issue..

Reply
avatar
admin
May 08, 2014 ×

Hi Lalit,
I have one issue nested gridview.In my first gridview contains submit button and third gridview contains two dropdowns and two textboxes.Now i want to validate those fields on first gridview submit button click.kindly do needfull.

Reply
avatar
admin

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily.. Out Of Topic Show Conversion CodeHide Conversion Code Show EmoticonHide Emoticon

Thanks for your comment