Article
    C#
    ADO.Net
    .NET
    ASP.Net & Web Forms
    Custom Controls
    Web Development
    Exception Handling
    XML
    Database
    Security in .Net
    Testing
    Web Services
    Windows Services
    Windows Controls
    WCF
    AJAX
    WPF
    XAML
    Reporting
    Setup
    VB.Net
    LINQ
    JQuery
    SilverLight
    JavaScript
    HTML5
    Crystal Report
    Cloud Computing
    Share Point
    Visual C++
    MVC
    Android
    PHP
    Java
    HTML
    WordPress
    Joomla
    Products
    Drupal
    Windows Phone
    JSON
    LightSwitch
    iPhone/iPad
    Ruby on Rails
    IIS 7
    Windows 8
    CSS/CSS3
    Excel
    MS Access
    Shortcut Keys
    Visual SourceSafe
    Team Foundation Server
    API(s)
    Sencha-Touch
    Single Page App
    Bootstrap
Follow Us
Follow _MindStick_ on Twitter View MindStick Software's LinkedIn profile View MindStick Software's Facebook profile
Top Contributor
Advertisement
Advertise with Us
Mindstick
Article Article  Forum Forum  Blog Blog  Quiz Quiz  Beginner Beginner  Careers Careers  Contact Contact  Login Login  
Home | Product | Services | About Us | Interview | DeveloperSection | Submit an Article | Submit Blog

Home >> ASP.Net & Web Forms >> Insert, Delete, Update in GridView in ASP.Net using C#
Insert, Delete, Update in GridView in ASP.Net using C#
Insert, Delete, Update in GridView in ASP.Net using C#


by AVADHESH PATEL on 8/6/2012 3:05:56 PM

Views: 93789       Comments: 35

Insert, Delete, Update in GridView in ASP.Net using C#

ASP.NET GridView is a very common and useful control. Here, I’m explaining how to work with GridView control in ASP.NET, like how to insert, delete and update record in GridView control. Follow bellow steps to know how to work with GridView in ASP.NET.

Step 1:- Create Database in SqlServer and create a table within this database. For demonstration here I have created database named “Demo” and table named “GridView”

CREATE DATABASE DEMO

GO

 

USE DEMO

GO

 

CREATE TABLE GridView

(

id INT PRIMARY KEY IDENTITY,

name VARCHAR (50) NOT NULL,

age INT NOT NULL,

salary FLOAT NOT NULL,

country VARCHAR(50) NOT NULL,

city VARCHAR(50) NOT NULL,

photopath VARCHAR(500) NULL

)

GO

 

Insert, Delete, Update in GridView in ASP.Net using C#

Note: Here “id” column is auto increment and primary key. 

Step 2:- Add connection string in your application’s web.config file and change name and connectionString according your SQL Server configuration as following.

<configuration>

     <connectionStrings>

                <add name="dbconnection" providerName="System.Data.SqlClient"

                    connectionString="Data Source=.;Initial Catalog=demo; User Id=xyz; password=123456" />

                </connectionStrings>

</configuration>

 

Step 3:- Drag & drop GridView control from Toolbox on “.aspx” page and write down the following line of code within <asp:GridView> section or simple copy the following line of code and put where you want to display GridVIew.

 

<div>

        <asp:GridView ID="GridView1" runat="server" ShowHeaderWhenEmpty="True"

            AutoGenerateColumns="False" onrowdeleting="RowDeleting"

            OnRowCancelingEdit="cancelRecord" OnRowEditing="editRecord"

            OnRowUpdating="updateRecord" CellPadding="4"

            EnableModelValidation="True" GridLines="None" Width="1297px"

            ForeColor="#333333" >

            <RowStyle HorizontalAlign="Center" />

            <AlternatingRowStyle BackColor="White" />

            <EditRowStyle BackColor="#7C6F57" />

            <FooterStyle BackColor="#1C5E55" ForeColor="White" Font-Bold="True" />

            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />

            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />

            <RowStyle BackColor="#E3EAEB" />

            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />

 

            <Columns>

 

            <asp:TemplateField>

            <HeaderTemplate>Id</HeaderTemplate>

            <ItemTemplate>

            <asp:Label ID ="lblId" runat="server" Text='<%#Bind("id")%>'></asp:Label>

            </ItemTemplate>

            </asp:TemplateField>

 

            <asp:TemplateField>

            <HeaderTemplate>Name</HeaderTemplate>

            <ItemTemplate>

            <asp:Label ID ="lblName" runat="server" Text='<%#Bind("name") %>'></asp:Label>

            </ItemTemplate>

            <EditItemTemplate>

            <asp:TextBox ID="txtName" runat="server" Text='<%#Bind("name") %>' MaxLength="50"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtName" runat="server" Text="*" ToolTip="Enter name" ControlToValidate="txtName"></asp:RequiredFieldValidator>

            <asp:RegularExpressionValidator ID="revtxtName" runat="server" Text="*" ToolTip="Enter alphabate " ControlToValidate="txtName" ValidationExpression="^[a-zA-Z'.\s]{1,40}$"></asp:RegularExpressionValidator>

           

            </EditItemTemplate>

            <FooterTemplate>

            <asp:TextBox ID="txtNewName" runat="server" MaxLength="50"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtNewName" runat="server" Text="*" ToolTip="Enter name" ControlToValidate="txtNewName"></asp:RequiredFieldValidator>

            <asp:RegularExpressionValidator ID="revtxtNewName" runat="server" Text="*" ToolTip="Enter alphabate " ControlToValidate="txtNewName" ValidationExpression="^[a-zA-Z'.\s]{1,40}$"></asp:RegularExpressionValidator>

          

            </FooterTemplate>

            </asp:TemplateField>

           

            <asp:TemplateField>

            <HeaderTemplate>Age</HeaderTemplate>

            <ItemTemplate>

            <asp:Label ID="lblAge" runat ="server" Text='<%#Bind("age") %>'></asp:Label>

            </ItemTemplate>

            <EditItemTemplate>

            <asp:TextBox ID ="txtAge" runat="server" Text='<%#Bind("age") %>' MaxLength="2"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtAge" runat="server" Text="*" ToolTip="Enter age" ControlToValidate="txtAge"></asp:RequiredFieldValidator>

            <asp:RegularExpressionValidator ID="revtxtAge" runat="server" Text="*" ToolTip="Enter numeric value" ControlToValidate="txtAge" ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>

          

            </EditItemTemplate>

            <FooterTemplate>

            <asp:TextBox ID="txtNewAge" runat="server" MaxLength="2"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtNewAge" runat="server" Text="*" ToolTip="Enter age" ControlToValidate="txtNewAge"></asp:RequiredFieldValidator>

            <asp:RegularExpressionValidator ID="revNewtxtAge" runat="server" Text="*" ToolTip="Enter numeric value" ControlToValidate="txtNewAge" ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>

            </FooterTemplate>

            </asp:TemplateField>

 

            <asp:TemplateField>

            <HeaderTemplate>Salary</HeaderTemplate>

            <ItemTemplate>

            <asp:Label ID = "lblSalary" runat="server" Text='<%#Bind("salary") %>'></asp:Label>

            </ItemTemplate>

            <EditItemTemplate>

            <asp:TextBox ID="txtSalary" runat="server" Text='<%#Bind("salary") %>'  MaxLength="10"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtSalary" runat="server" Text="*"  ToolTip="Enter salary" ControlToValidate="txtSalary"></asp:RequiredFieldValidator>

            <asp:RegularExpressionValidator ID="revtxtSalary" runat="server" Text="*" ToolTip="Enter numeric value" ControlToValidate="txtSalary" ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>

          

            </EditItemTemplate>

            <FooterTemplate>

            <asp:TextBox ID="txtNewSalary" runat="server" MaxLength="10"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtNewSalary" runat="server" Text="*"  ToolTip="Enter salary" ControlToValidate="txtNewSalary"></asp:RequiredFieldValidator>

            <asp:RegularExpressionValidator ID="revtxtNewSalary" runat="server" Text="*" ToolTip="Enter numeric value" ControlToValidate="txtNewSalary" ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>

            </FooterTemplate>

            </asp:TemplateField>

 

            <asp:TemplateField>

            <HeaderTemplate>Country</HeaderTemplate>

            <ItemTemplate>

            <asp:Label ID = "lblCountry" runat="server" Text='<%#Bind("country") %>'></asp:Label>

            </ItemTemplate>

            <EditItemTemplate>

            <asp:TextBox ID="txtCountry" runat="server" Text='<%#Bind("country") %>' MaxLength="20"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtCountry" runat="server" Text="*" ToolTip="Enter country" ControlToValidate="txtCountry"></asp:RequiredFieldValidator>

        

            </EditItemTemplate>

            <FooterTemplate>

            <asp:TextBox ID="txtNewCountry" runat="server" MaxLength="20"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtNewCountry" runat="server" Text="*" ToolTip="Enter country" ControlToValidate="txtNewCountry"></asp:RequiredFieldValidator>

            </FooterTemplate>

            </asp:TemplateField>

 

            <asp:TemplateField>

            <HeaderTemplate>City</HeaderTemplate>

            <ItemTemplate>

            <asp:Label ID = "lblCity" runat="server" Text='<%#Bind("city") %>'></asp:Label>

            </ItemTemplate>

            <EditItemTemplate>

            <asp:TextBox ID="txtCity" runat="server" Text='<%#Bind("city") %>' MaxLength="20"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtCity" runat="server" Text="*" ToolTip="Enter city" ControlToValidate="txtCity"></asp:RequiredFieldValidator>

            </EditItemTemplate>

            <FooterTemplate>

            <asp:TextBox ID="txtNewCity" runat="server" MaxLength="20"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtNewCity" runat="server" Text="*" ToolTip="Enter city" ControlToValidate="txtNewCity"></asp:RequiredFieldValidator>

            </FooterTemplate>

            </asp:TemplateField>

 

            <asp:TemplateField>

            <HeaderTemplate>Photo</HeaderTemplate>

            <ItemTemplate>

            <asp:Image ID="imgPhoto" Width="100px" Height="100px" runat="server" text="Photo" ImageUrl='<%#Bind("photopath") %>' />

            </ItemTemplate>

            <EditItemTemplate>

            <asp:FileUpload ID="fuPhoto" runat="server" ToolTip="select Employee Photo"/>

            <asp:RegularExpressionValidator ID="revfuPhoto" runat="server" Text="*" ToolTip="Image formate only" ControlToValidate="fuPhoto" ValidationExpression="[a-zA-Z0_9].*\b(.jpeg|.JPEG|.jpg|.JPG|.jpe|.JPE|.png|.PNG|.mpp|.MPP|.gif|.GIF)\b"></asp:RegularExpressionValidator>

            </EditItemTemplate>

            <FooterTemplate>

            <asp:FileUpload ID="fuNewPhoto" runat="server" ToolTip="select Employee Photo"/>

            <asp:RequiredFieldValidator ID="rfvfuNewPhoto" runat="server" ErrorMessage="*" ToolTip="Select Photo" ControlToValidate="fuNewPhoto"></asp:RequiredFieldValidator>

            <asp:RegularExpressionValidator ID="revfuNewPhoto" runat="server" Text="*" ToolTip="Image formate only" ControlToValidate="fuNewPhoto" ValidationExpression="[a-zA-Z0_9].*\b(.jpeg|.JPEG|.jpg|.JPG|.jpe|.JPE|.png|.PNG|.mpp|.MPP|.gif|.GIF)\b"></asp:RegularExpressionValidator>

            </FooterTemplate>

            </asp:TemplateField>

 

            <asp:TemplateField>

            <HeaderTemplate>Operation</HeaderTemplate>

            <ItemTemplate>

            <asp:Button ID="btnEdit" runat="server" CommandName="Edit" Text="Edit" />

            <asp:Button ID="btnDelete" runat="server" CommandName="Delete" Text="Delete" CausesValidation="true" OnClientClick="return confirm('Are you sure?')" />

            </ItemTemplate>

            <EditItemTemplate>

            <asp:Button ID="btnUpdate" runat="server" CommandName="Update" Text="Update" />

            <asp:Button ID="btnCancel" runat="server" CommandName="Cancel" Text="Cancel" CausesValidation="false" />

            </EditItemTemplate>

 

            <FooterTemplate>

            <asp:Button ID="btnNewInsert" runat="server" Text="Insert" OnClick="InsertNewRecord"/>

            <asp:Button ID="btnNewCancel" runat="server" Text="Cancel" OnClick="AddNewCancel" CausesValidation="false" />

            </FooterTemplate>        

            </asp:TemplateField>           

            </Columns>

            <EmptyDataTemplate>

                      No record available                    

            </EmptyDataTemplate>       

        </asp:GridView>

        <br />

        <asp:Button ID="btnAdd" runat="server" Text="Add New Record" OnClick="AddNewRecord" />  

    </div>

 

Step 4:- Create one class within App_Code folder. Here I have given this class named is GlobalClass and write following line of code.

using System.Data;

using System.Data.SqlClient;

 

public class GlobalClass

{

    public static SqlDataAdapter adap;

    public static DataTable dt;

    // Stored image path before updating the record

    public static string imgEditPath;

}

 

Step 5:- Create one folder, named Images, where we have stored employees photos see in following image.

Insert, Delete, Update in GridView in ASP.Net using C#

Step 6:- Write down following line of code in “.cspage which related to your .aspx page (e.g. if your .aspx page name is default.aspx then your .cs file is default.aspx.cs).

using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Web.UI.WebControls;

using System.IO;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            // Call FillGridView Method

            FillGridView();

        }

    }

    /// <summary>

    /// Fill record into GridView

    /// </summary>

    public void FillGridView()

    {

        try

        {

            string cnString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;

            SqlConnection con = new SqlConnection(cnString);

            GlobalClass.adap = new SqlDataAdapter("select * from gridview", con);

            SqlCommandBuilder bui = new SqlCommandBuilder(GlobalClass.adap);

            GlobalClass.dt = new DataTable();

            GlobalClass.adap.Fill(GlobalClass.dt);

            GridView1.DataSource = GlobalClass.dt;

            GridView1.DataBind();

        }

        catch

        {

            Response.Write("<script> alert('Connection String Error...') </script>");

        }

    }

    /// <summary>

    /// Edit record

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void editRecord(object sender, GridViewEditEventArgs e)

    {

        // Get the image path for remove old image after update record

        Image imgEditPhoto = GridView1.Rows[e.NewEditIndex].FindControl("imgPhoto") as Image;

        GlobalClass.imgEditPath = imgEditPhoto.ImageUrl;

        // Get the current row index for edit record

        GridView1.EditIndex = e.NewEditIndex;

        FillGridView();

    }

 

    /// <summary>

    /// Cancel the operation (e.g. edit)

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void cancelRecord(object sender, GridViewCancelEditEventArgs e)

    {

        GridView1.EditIndex = -1;

        FillGridView();

    }

 

    /// <summary>

    /// Add new row into DataTable if no record found in Table

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void AddNewRecord(object sender, EventArgs e)

    {

        try

        {

            if (GlobalClass.dt.Rows.Count > 0)

            {

                GridView1.EditIndex = -1;

                GridView1.ShowFooter = true;

                FillGridView();

            }

            else

            {

                GridView1.ShowFooter = true;

                DataRow dr = GlobalClass.dt.NewRow();

                dr["name"] = "0";

                dr["age"] = 0;

                dr["salary"] = 0;

                dr["country"] = "0";

                dr["city"] = "0";

                dr["photopath"] = "0";

                GlobalClass.dt.Rows.Add(dr);

                GridView1.DataSource = GlobalClass.dt;

                GridView1.DataBind();

                GridView1.Rows[0].Visible = false;

            }

        }

        catch

        {

            Response.Write("<script> alert('Row not added in DataTable...') </script>");

        }

    }

 

    /// <summary>

    /// Cancel new added record

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void AddNewCancel(object sender, EventArgs e)

    {

        GridView1.ShowFooter = false;

        FillGridView();

    }

 

    /// <summary>

    /// Insert New Record

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void InsertNewRecord(object sender, EventArgs e)

    {

        try

        {

            string strName = GlobalClass.dt.Rows[0]["name"].ToString();

            if (strName == "0")

            {

                GlobalClass.dt.Rows[0].Delete();

                GlobalClass.adap.Update(GlobalClass.dt);

            }

            TextBox txtName = GridView1.FooterRow.FindControl("txtNewName") as TextBox;

            TextBox txtAge = GridView1.FooterRow.FindControl("txtNewAge") as TextBox;

            TextBox txtSalary = GridView1.FooterRow.FindControl("txtNewSalary") as TextBox;

            TextBox txtCountry = GridView1.FooterRow.FindControl("txtNewCountry") as TextBox;

            TextBox txtCity = GridView1.FooterRow.FindControl("txtNewCity") as TextBox;

            FileUpload fuPhoto = GridView1.FooterRow.FindControl("fuNewPhoto") as FileUpload;

            Guid FileName = Guid.NewGuid();

            fuPhoto.SaveAs(Server.MapPath("~/Images/" + FileName + ".png"));

            DataRow dr = GlobalClass.dt.NewRow();

            dr["name"] = txtName.Text.Trim();

            dr["age"] = txtAge.Text.Trim();

            dr["salary"] = txtSalary.Text.Trim();

            dr["country"] = txtCountry.Text.Trim();

            dr["city"] = txtCity.Text.Trim();

            dr["photopath"] = "~/Images/" + FileName + ".png";

            GlobalClass.dt.Rows.Add(dr);

            GlobalClass.adap.Update(GlobalClass.dt);

            GridView1.ShowFooter = false;

            FillGridView();

        }

        catch

        {

            Response.Write("<script> alert('Record not added...') </script>");

        }

 

    }

    /// <summary>

    /// Update the record

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void updateRecord(object sender, GridViewUpdateEventArgs e)

    {

        try

        {

            TextBox txtName = GridView1.Rows[e.RowIndex].FindControl("txtName") as TextBox;

            TextBox txtAge = GridView1.Rows[e.RowIndex].FindControl("txtAge") as TextBox;

            TextBox txtSalary = GridView1.Rows[e.RowIndex].FindControl("txtSalary") as TextBox;

            TextBox txtCountry = GridView1.Rows[e.RowIndex].FindControl("txtCountry") as TextBox;

            TextBox txtCity = GridView1.Rows[e.RowIndex].FindControl("txtCity") as TextBox;

            FileUpload fuPhoto = GridView1.Rows[e.RowIndex].FindControl("fuPhoto") as FileUpload;

            Guid FileName = Guid.NewGuid();

            if (fuPhoto.FileName != "")

            {

                fuPhoto.SaveAs(Server.MapPath("~/Images/" + FileName + ".png"));

                GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["photopath"] = "~/Images/" + FileName + ".png";

                File.Delete(Server.MapPath(GlobalClass.imgEditPath));

            }

            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["name"] = txtName.Text.Trim();

            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["age"] = Convert.ToInt32(txtAge.Text.Trim());

            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["salary"] = Convert.ToInt32(txtSalary.Text.Trim());

            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["country"] = txtCountry.Text.Trim();

            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["city"] = txtCity.Text.Trim();

            GlobalClass.adap.Update(GlobalClass.dt);   

            GridView1.EditIndex = -1;

            FillGridView();

        }

        catch

        {

            Response.Write("<script> alert('Record updation fail...') </script>");

        }

    }

 

    /// <summary>

    /// Delete Record

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void RowDeleting(object sender, GridViewDeleteEventArgs e)

    {

        try

        {

            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex].Delete();

            GlobalClass.adap.Update(GlobalClass.dt);

            // Get the image path for removing deleted's record image from server folder

            Image imgPhoto = GridView1.Rows[e.RowIndex].FindControl("imgPhoto") as Image;

            File.Delete(Server.MapPath(imgPhoto.ImageUrl));

            FillGridView();

        }

        catch

        {

            Response.Write("<script> alert('Record not deleted...') </script>");

        }

    }

}

 

Step 7:- Now, save and build you application and execute. Your application output display as following.

Insert, Delete, Update in GridView in ASP.Net using C#

It’s your application first screen. Because there is not data in table so it displace message “No record available”.

Step 8:- For inserting data, click on button “Add New Record”. Now fill the data. Every controls have validation for prohibited wrong input.  

Insert, Delete, Update in GridView in ASP.Net using C#

After filling data, your GridView looking as following.  Here I have inserted three records.

Insert, Delete, Update in GridView in ASP.Net using C#

Note: - Id are generated automatic for every new record.

Step 9:- For updating records click button “Edit” and change TextBox Data and you can select new photo of employee. For example in place of age “28”, updated with “30” and in place of salary “50000”, updated with “55000”, then click button “Update”. Through button “Cancel” you return previous stage.

Insert, Delete, Update in GridView in ASP.Net using C#

Step 10:- For record deletion, click on button “Delete”. Before deleting record, confirmation alert message are popup. Here I have deleted 3rd record (e.g. Andrew Deniel). After deleting record your GridView looks as following.

Insert, Delete, Update in GridView in ASP.Net using C#

Report Abuse Form
Reason:    
 


Please help
by toan buivan 11/22/2012 10:00:46 AM
Sir i'm is a newbie studing asp.net and i dont know where is the global class  GlobalClass in your post to understand

(sorry my English is bad)

Report Abuse

global class
by AVADHESH PATEL 11/24/2012 12:06:29 AM
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class GlobalClass
{
    public static int autoId;
    public static SqlDataAdapter adap;
    public static DataTable dt;
}
Report Abuse

While click on Add New Record,i m getting this type of Error message--Object reference not set to an instance of an object.kindly follow the below code and tell me where exactly i need to declare the Global Class
by kamal pradhan 12/28/2012 12:06:48 PM
Dear Sir,
  Kindly help me,where exactly i need to declare Global Class and while click on Add New Record,its throwing Error--Object reference not set to an instance of an object.please follow the below code,if any solution u get,kindly mail me in this below email id- kamalsekhar@hotmail.com.sp i will be greateful to u.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public class GlobalClass
        {
            public static int autoId;
            public static SqlDataAdapter adap;
            public static DataTable dt;
        }

namespace GridViewExample
{
    public partial class GridviewEx : System.Web.UI.Page
    {
                protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillGridView();
            }
        }
------------------------------------------------------------------
protected void AddNewRecord(object sender, EventArgs e)
        {
            try
            {
                if (GlobalClass.dt.Rows.Count > 0)
                {
                    GridView1.EditIndex = -1;
                    GridView1.ShowFooter = true;
                    FillGridView();
                }
                else
                {
                    GridView1.ShowFooter = true;
                    DataRow dr = GlobalClass.dt.NewRow();
                    dr[1] = "0";
                    dr[2] = 0;
                    dr[3] = 0;
                    dr[4] = "0";
                    dr[5] = "0";
                    GlobalClass.dt.Rows.Add(dr);
                    GridView1.DataSource = GlobalClass.dt;
                    GridView1.DataBind();
                    GridView1.Rows[0].Visible = false;

                }

            }
            catch(Exception ex)
            {

            }
        }
Report Abuse

Re, Insert, Delete, Update in GridView in ASP.Net using C#
by AVADHESH PATEL 1/5/2013 12:15:28 AM
Hi Kamal Pradhan

You can create GlobalClass in App_Code folder. Add one cs file and set that name GlobalClass.cs

and write below code.

using System.Data;
using System.Data.SqlClient;

public class GlobalClass
{
    public static int autoId;
    public static SqlDataAdapter adap;
    public static DataTable dt;
}
Report Abuse

app_code folder is not there in visual studio 2008
by Feby Raju 1/5/2013 2:56:31 AM
sir, I couldn't find the app_code folder,. also i tried to add it one. but its not there in the list.
do app_globalresource work????
pls help
Report Abuse

how to edit images in gridview with database using asp.net
by anil babu 6/17/2013 8:36:44 AM
I have one more column Image in database,
In the same way I want to Edit the images After edit images Save to database using Asp.net gridview.How can i do this please give me the remaining code also
Report Abuse

Re: how to edit images in gridview with database using asp.net
by AVADHESH PATEL 6/19/2013 3:18:17 AM

Hi Anil Babu,

I have updated this article. Now you can save, update and delete image in GridView in ASP.NET. Try this then tell me, what happened! I hope it help you.

Report Abuse

how to edit images in gridview with database using asp.net
by anil babu 6/19/2013 4:10:01 AM
Running this project at the time of inserting data entering all fields data Clicking insert,Update action not working
Report Abuse

re : how to edit images in gridview with database using asp.net
by AVADHESH PATEL 6/19/2013 4:36:31 AM
Hi Anil,

How to do this? On my side it's working fine. Can you provide exact error message or error screen shot for better understanding. 
Report Abuse

how to edit images in gridview with database using asp.net
by anil babu 6/19/2013 4:48:28 AM
I am running local,How to send screen shot?
At the time time of adding new record enter All fields data next click to Insert Button data not stored to database,
Not getting any error
Report Abuse

Re: how to edit images in gridview with database using asp.net
by AVADHESH PATEL 6/19/2013 6:20:19 AM
Hi Anil,

Re-Check your connection string or debug your application and tell what error are generated?

You can get the screen shot using "PrtScr" (Print Screen) key. When error come, press the "PrtScr" from your keyboard and paste the image on MS Paint. Here you note down error or modify image and send me. 
Report Abuse

how to edit images in gridview with database using asp.net
by anil babu 6/19/2013 6:30:36 AM
I am taking screen shot
There is no option for sending image to u
Report Abuse

re: how to edit images in gridview with database using asp.net
by AVADHESH PATEL 6/19/2013 7:44:30 AM
Hi Anil,

Take Screen shot of Error and upload it on following website 

after uploading image get the image url (online path used google chrome for better performance) and used this image url on this forum section. For uploading image on this forum, select image option as following image. 


If any problem to send error screen shot then send error message. 
Report Abuse

how to edit images in gridview with database using asp.net
by anil babu 6/19/2013 8:24:25 AM
after enter data click insert button not working
Report Abuse

re: how to edit images in gridview with database using asp.net
by AVADHESH PATEL 6/19/2013 8:59:38 AM
Hi Anil,

According your screen shot, there are validation error, It may be you are uploading image on incorrect format (e.g. jpg, png or other image format) or invalid location path. Check it and try again.

If image format is correct then put break point at "InsertNewRecord" method and debug you application and tell me what error generated now. If FileUpload validation create problem then comment the "RegularExpressionValidation" (FileUpload id is revfuNewPhoto and revfuPhoto) and try again. 
Report Abuse

Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
by Nilesh Jagtap 6/20/2013 3:27:47 AM
hello sir,

I hv copied your code above , I am getting error at update operation, - 'Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.'

please help 

thanks in advance
nilesh
Report Abuse

re: Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
by AVADHESH PATEL 6/20/2013 7:13:51 AM
Hi Nilesh,

You are missing primary key in table. Recreate your table and set "id" column as Primary Key with Identity Column. If you are using another table then set one column as Primary Key for update and delete, then tell me what append! 
Report Abuse

C# code
by subramaniyam krish 7/17/2013 11:22:15 PM
how to find row number in data table using primary key in C#
Report Abuse

error
by Umadevi Achanta 8/27/2013 3:44:40 AM
Hi Patel,
I am getting error while i m running the application and when I tried to add the record. I added screen shots for reference. If could help me in solving this it will be appreciated. Thanks.

Report Abuse

Got
by Umadevi Achanta 8/27/2013 4:29:07 AM
Got it finally. very good example for starters. Thnaks a lot.
Report Abuse

nice
by Johnny Depp 11/12/2013 1:20:29 AM
nice
Report Abuse

dropdown list and checkbox
by caroline kavya 12/15/2013 11:53:15 PM
Can you help me in inserting dropdown list and checkbox in the given code.
Report Abuse

why iam not able to store the data in database
by ashwini dharamsale 1/21/2014 7:49:28 AM
why iam not able to store the data in database
Report Abuse

error
by sakthinathan sakthi 2/17/2014 6:14:17 AM
Dear Sir,
               i get the connecting string error plz solve
Report Abuse

erro
by Luu Tran 2/22/2014 12:49:25 AM
I cannot insert and update. in my databate, table product at id I don't choose  auto increment for id. I think it have erro at Index. but I cannot repair it. so do you help me. thank you!
Report Abuse

erro
by Luu Tran 2/22/2014 12:52:11 AM
I cannot insert and update. in my databate, table product at id I don't choose  auto increment for id. I think it have erro at Index. but I cannot repair it. so do you help me? thank you!
Report Abuse

Error in Editing
by chitra parmar 3/5/2014 11:31:12 PM
Hello Sir,
Your code works fine but whenever I try to edit any row, the rows below that row become invisible.
Why is this happening ??

Hope to get your reply soon.
Thanks in Advance.
Report Abuse

Its working
by Muhammad Usman 3/11/2014 9:55:25 PM
This is really an informative post.
Thanks a lot for sharing this great stuff.
Fee Download Student Projects with Code!
Report Abuse

Paging & Sorting with gird view
by Umesh Chand Daiya 5/31/2014 8:08:29 PM
Respected Sir,
Its working properly now i want to use paging with gridview and sorting with this grid view. after completion of this i would like to know if there will be a lot of field in table than in insert and update mode there should be open a new panel.
Plz reply soon
Thanks & Regards
Umesh Chand Daiya
Report Abuse

Need this code for Access Database
by Prasath V 7/11/2014 2:49:35 AM
hi folk....
 so far i followed u. i'm tried to convert code from SQL to ACCESS Database. so please help me friend.
mail me the solution to csevprasath@live.com
Report Abuse

Error in Update
by Nicky Pike 8/8/2014 3:14:13 PM

First off, thank you for this post. Very helpful!!

All methods are working except for row update/edit. When I attempt to edit a row, I get the error "Input string not the correct format". The column I'm getting the break on is QTY, which is of type Int32 in the DB. I've done the Convert.ToInt32 as you did on the age, but still the same error.

Thoughts? Code with break highlighted below:

protected void updateRecord(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            TextBox txtQTY = GridView1.FooterRow.FindControl("txtNewQTY") as TextBox;
            TextBox txtPartNumber = GridView1.FooterRow.FindControl("txtNewPartNumber") as TextBox;
            TextBox txtSKU = GridView1.FooterRow.FindControl("txtNewSKU") as TextBox;

            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["QTY"] = Convert.ToInt32(txtQTY.Text.Trim());
            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["Part_Number"] = txtPartNumber.Text.Trim();
            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["SKU"] = txtSKU.Text.Trim();
            GlobalClass.sqlAdapt.Update(GlobalClass.dt);
            GridView1.EditIndex = -1;
            FillGridView();
               
        }
        catch (System.ArgumentException ex)
        {
            Response.Write(ex.Message);
        }
        catch (System.FormatException ex)
        {
            Response.Write(ex.Message);
            Response.Write(ex.Source);
            Response.Write(ex.InnerException);
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            Response.Write(ex.Message);
        }
    }

Report Abuse

Error in Update
by John Smith 8/8/2014 11:24:59 PM
Nicky
Have you checked for the NULL value?
Report Abuse

Error in Update
by Nicky Pike 8/11/2014 9:56:22 AM

John,

No I hadn't, but decided to try something based on your suggestion. I set txtQTY equal to 20 in the code and the update worked, however, all my other fields were reset to nulls. So based on that, I'm assuming that the code is not picking up the values for me and everything is null. Since int32 can't be null, the error.

So now, I guess I need to figure out why my code isn't retrieving the values on the update.


Report Abuse

Error in Update
by Nicky Pike 8/11/2014 10:00:21 AM

John,

I figured it out!

I wasn't getting the values from the gridview correctly. Your recommendation on looking for Null is what led me to the solution.  I was attempting to get the values from the footerrow (which didn't exist), not from the actual rows themselves.  Thank you!!! 

Nicky

Report Abuse

Error in Update
by John Smith 8/11/2014 11:11:33 PM
Good to hear that Buddy!!!
Happy Coding :)
Report Abuse
Title :
Comment :
Text ColorBackground Color
BoldItalicUnderline
LeftCenterRightJustify
Ordered ListBulleted List
IndentOutdent
Horizontal Rule
SubscriptSuperscript
HyperlinkImage
Design ModeDesign
View HtmlHtml
     
 
Latest Article by AVADHESH PATELRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Latest BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Top Viewed ArticlesRSS Feed
    
    
    
    
    
    
    
    
    
    
Top Viewed BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
Latest Interview QuestionsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Total Online Users: 4281
Advertisement
MindStick DataConver
Advertise with Us
  
Copyright © 2009 - 2014MindStick. All Rights Reserved.