Home > DeveloperSection > Articles > Insert, Delete, Update in GridView in ASP.Net using C#

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

Posted by  AVADHESH PATEL
on    August-06-2012 15:05 PM

ASP.Net ASP.Net 
Ratings:
39 Comment(s)
 104056  View(s)
Rate this:

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” columnis 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 controlfrom Toolboxon “.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” youreturn 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#


Please help

By toan buivan on   2 years ago
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)


global class

By AVADHESH PATEL on   2 years ago
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;
}

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 on   one year ago
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)
            {

            }
        }

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

By AVADHESH PATEL on   one year ago
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;
}

app_code folder is not there in visual studio 2008

By Feby Raju on   one year ago
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

how to edit images in gridview with database using asp.net

By anil babu on   one year ago
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

Re: how to edit images in gridview with database using asp.net

By AVADHESH PATEL on   one year ago

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.


how to edit images in gridview with database using asp.net

By anil babu on   one year ago
Running this project at the time of inserting data entering all fields data Clicking insert,Update action not working

re : how to edit images in gridview with database using asp.net

By AVADHESH PATEL on   one year ago
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. 

how to edit images in gridview with database using asp.net

By anil babu on   one year ago
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

Re: how to edit images in gridview with database using asp.net

By AVADHESH PATEL on   one year ago
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. 

how to edit images in gridview with database using asp.net

By anil babu on   one year ago
I am taking screen shot
There is no option for sending image to u

re: how to edit images in gridview with database using asp.net

By AVADHESH PATEL on   one year ago
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. 

how to edit images in gridview with database using asp.net

By anil babu on   one year ago
after enter data click insert button not working

re: how to edit images in gridview with database using asp.net

By AVADHESH PATEL on   one year ago
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. 

Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.

By Nilesh Jagtap on   one year ago
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

re: Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.

By AVADHESH PATEL on   one year ago
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! 

C# code

By subramaniyam krish on   one year ago
how to find row number in data table using primary key in C#

error

By Umadevi Achanta on   one year ago
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.


Got

By Umadevi Achanta on   one year ago
Got it finally. very good example for starters. Thnaks a lot.

nice

By Johnny Depp on   one year ago
nice

dropdown list and checkbox

By caroline kavya on   11 months ago
Can you help me in inserting dropdown list and checkbox in the given code.

why iam not able to store the data in database

By ashwini dharamsale on   10 months ago
why iam not able to store the data in database

error

By sakthinathan sakthi on   9 months ago
Dear Sir,
               i get the connecting string error plz solve

erro

By Luu Tran on   9 months ago
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!

erro

By Luu Tran on   9 months ago
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!

Error in Editing

By chitra parmar on   8 months ago
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.

Its working

By Muhammad Usman on   8 months ago
This is really an informative post.
Thanks a lot for sharing this great stuff.
Fee Download Student Projects with Code!

Paging & Sorting with gird view

By Umesh Chand Daiya on   5 months ago
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

Need this code for Access Database

By Prasath V on   4 months ago
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

Error in Update

By Nicky Pike on   3 months ago

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);
        }
    }


Error in Update

By John Smith on   3 months ago
Nicky
Have you checked for the NULL value?

Error in Update

By Nicky Pike on   3 months ago

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.



Error in Update

By Nicky Pike on   3 months ago

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


Error in Update

By John Smith on   3 months ago
Good to hear that Buddy!!!
Happy Coding :)

Problems with GlobalClass in App_Code

By Denise Okay on   2 months ago
I know this thread is old but it's the best one I've found to create what I'm trying to do.  I have followed the steps exactly except that I can't get the GlobalClass.cs included in my WebForm code behind.  I created the class in App_Code; should the Build Action be "Compile" or "Content"? 

FillGridView() works fine, and when I click Edit I get the textboxes I'm expecting.  But when I try to Update or Add New, I get 

System.NullReferenceException: Object reference not set to an instance of an object. at ResearchProject.WebForm9.AddNewRecord(Object sender, EventArgs e) in c:\Projects\WebForm9.aspx.cs:line 88

I didn't get the GlobalClass to work out so I declared these fields in WebForm9.aspx.cs:
        public static MySqlConnection connection;
        public static MySqlDataAdapter myDataAdapter;
        public static DataTable dt;


Any help is appreciated.  I feel I am so close to getting this resolved!

EDIT
I referenced GlobalClass using namespace.App_Code.GlobalClass in my aspx.cs file and it is recognized now.  I set the BuildAction to Compile.  However I am getting the same error message on Add and Update.  

update delete not working

By pramod mishra on   20 days ago
update delete not working saying message Record not deleted...and Record updation fail.. also primary key that is ID not automatically insert.  please help me.. i have project to submit in few days.

UPDATE DELETE NOT WORKING>>>> HELP ME,,,,

By pramod mishra on   20 days ago
update delete not working saying message Record not deleted...and Record updation fail.. also primary key that is ID not automatically insert.  please help me.. i have project to submit in few days.

update delete not working

By John Smith on   19 days ago
Pramod, upload your code here















Recent Activities



Maria Susan Created New Discussion Issue with open tab group in titanium   15 hours ago

Sumit Kesarwani added new Question What is the serialization?   4 days ago

Don't want to miss updates? Please click the below button!