Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8911083
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T03:51:04+00:00 2026-06-15T03:51:04+00:00

I want to display,insert,update,delete in DataGrid (Asp.net and Sqlserver2008) and then i want to

  • 0

I want to display,insert,update,delete in DataGrid (Asp.net and Sqlserver2008) and then i want to export data from datagrid to excel file.
Table Structure

Default.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_Default" EnableEventValidation="false"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>'A'</title>
    <style type="text`/css">`
     .Gridview
        {
            font-family: Verdana;
            font-size: 10pt;
            font-weight: normal;
            color: black;
        }
    </style>

    <script type="text/javascript">
        function ConfirmationBox(username) {

            var result = confirm('Are you sure you want to delete ' + username + ' Details?');
            if (result) {

                return true;
            }
            else {
                return false;
            }
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvDetails" DataKeyNames="UserId,UserName" runat="server" AutoGenerateColumns="false"
            CssClass="Gridview" HeaderStyle-BackColor="#61A6F8" ShowFooter="true" HeaderStyle-Font-Bold="true"
            HeaderStyle-ForeColor="White" OnRowCancelingEdit="gvDetails_RowCancelingEdit"
            OnRowDeleting="gvDetails_RowDeleting" OnRowEditing="gvDetails_RowEditing" 
            OnRowUpdating="gvDetails_RowUpdating"
            OnRowCommand="gvDetails_RowCommand" Height="275px" Width="530px">
            <Columns>
                <asp:TemplateField>
                    <EditItemTemplate>
                        <asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" 
                            ImageUrl="~/Images/update.jpg" ToolTip="Update" Height="20px" Width="20px" />
                        <asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" 
                            ImageUrl="~/Images/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" 
                            ImageUrl="~/Images/Edit.jpg" ToolTip="Edit" Height="20px" Width="20px" />
                        <asp:ImageButton ID="imgbtnDelete" CommandName="Delete" runat="server" 
                            ImageUrl="~/Images/delete.jpg" ToolTip="Delete" Height="20px" Width="20px" />
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/AddNewitem.jpg"
                            CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="UserName">
                    <EditItemTemplate>
                        <asp:Label ID="lbleditusr" runat="server" Text='<%#Eval("Username") %>' />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblitemUsr" runat="server" Text='<%#Eval("UserName") %>' />
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtftrusrname" runat="server" />
                        <asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="txtftrusrname"
                            Text="*" ValidationGroup="validaiton" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtcity" runat="server" Text='<%#Eval("City") %>' />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblcity" runat="server" Text='<%#Eval("City") %>' />
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtftrcity" runat="server" />
                        <asp:RequiredFieldValidator ID="rfvcity" runat="server" ControlToValidate="txtftrcity"
                            Text="*" ValidationGroup="validaiton" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Designation">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtstate" runat="server" Text='<%#Eval("Designation") %>' />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblstate" runat="server" Text='<%#Eval("Designation") %>' />
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtftrDesignation" runat="server" />
                        <asp:RequiredFieldValidator ID="rfvdesignation" runat="server" ControlToValidate="txtftrDesignation"
                            Text="*" ValidationGroup="validaiton" />
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>

<HeaderStyle BackColor="#61A6F8" Font-Bold="True" ForeColor="White"></HeaderStyle>
        </asp:GridView>
    </div>
    <div>
        <asp:Label ID="lblresult" runat="server"></asp:Label>
    </div>
    <div>
        <asp:Button ID="btn_Excel" runat="server" Text="Excel" 
            onclick="btn_Excel_Click" />
    </div>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Reflection;
using System.IO;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
    private SqlConnection con = new SqlConnection("Data Source=.;uid=sa;pwd=sa123;database=Example1");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindEmployeeDetails();
        }
    }
    protected void BindEmployeeDetails()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        if (ds.Tables[0].Rows.Count > 0)
        {
            gvDetails.DataSource = ds;
            gvDetails.DataBind();
        }
        else
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            gvDetails.DataSource = ds;
            gvDetails.DataBind();
            int columncount = gvDetails.Rows[0].Cells.Count;
            gvDetails.Rows[0].Cells.Clear();
            gvDetails.Rows[0].Cells.Add(new TableCell());
            gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
            gvDetails.Rows[0].Cells[0].Text = "No Records Found";
        }
    }
    protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvDetails.EditIndex = e.NewEditIndex;
        BindEmployeeDetails();
    }
    protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
        string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
        TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtcity");
        TextBox txtDesignation = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtstate");
        con.Open();
        SqlCommand cmd = new SqlCommand("update Employee_Details set City='" + txtcity.Text + "',Designation='" + txtDesignation.Text + "' where UserId=" + userid, con);
        cmd.ExecuteNonQuery();
        con.Close();
        lblresult.ForeColor = Color.Green;
        lblresult.Text = username + " Details Updated successfully";
        gvDetails.EditIndex = -1;
        BindEmployeeDetails();
    }

    protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvDetails.EditIndex = -1;
        BindEmployeeDetails();
    }

    protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
        string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
        con.Open();
        SqlCommand cmd = new SqlCommand("delete from Employee_Details where UserId=" + userid, con);
        int result = cmd.ExecuteNonQuery();
        con.Close();
        if (result == 1)
        {
            BindEmployeeDetails();
            lblresult.ForeColor = Color.Blue;
            lblresult.Text = username + " details deleted successfully";
        }
    }

    protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //getting username from particular row
            string username = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "UserName"));
            //identifying the control in gridview
            ImageButton lnkbtnresult = (ImageButton)e.Row.FindControl("imgbtnDelete");
            //raising javascript confirmationbox whenver user clicks on link button
            if (lnkbtnresult != null)
            {
                lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + username + "')");
            }
        }
    }

    protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("AddNew"))
        {
            TextBox txtUsrname = (TextBox)gvDetails.FooterRow.FindControl("txtftrusrname");
            TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl("txtftrcity");
            TextBox txtDesgnation = (TextBox)gvDetails.FooterRow.FindControl("txtftrDesignation");
            con.Open();
            SqlCommand cmd =
                new SqlCommand("insert into Employee_Details(UserName,City,Designation) values('"
                    + txtUsrname.Text + "','" + txtCity.Text + "','" + txtDesgnation.Text + "')", con);
            int result = cmd.ExecuteNonQuery();
            con.Close();
            if (result == 1)
            {
                BindEmployeeDetails();
                lblresult.ForeColor = Color.Blue;
                lblresult.Text = txtUsrname.Text + " Details inserted successfully";
            }
            else
            {
                lblresult.ForeColor = Color.Red;
                lblresult.Text = txtUsrname.Text + " Details not inserted";
            }
        }
    }
    protected void btn_Excel_Click(object sender, EventArgs e)
    {
        this.gvDetails.AllowPaging = false;
        this.gvDetails.AllowSorting = false;
        this.gvDetails.EditIndex = -1;
        this.BindEmployeeDetails();
        Response.Clear();
        Response.ContentType = "application/vnd.xls";
        Response.AddHeader("content-disposition", "attachment;filename=MyList.xls");
        Response.Charset = "";
        StringWriter swriter = new StringWriter();
        HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
        gvDetails.RenderControl(hwriter);
        Response.Write(swriter.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //to Render Control
    }
}

My code works fine.
But my excel file looks like this
Excel output

So i don’t want the images in datagrid to be exported.
How can i do that.
Kindly reply.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T03:51:05+00:00Added an answer on June 15, 2026 at 3:51 am

    Ok i got the solution (From a colleague).
    Please vote my answer if its correct.
    Explanation:
    1.We have to first make a temporary table.
    2.Now add only the required column from datagrid.
    3.Use temporary table to Export data in Excel.

    Code:In the Button click call the function ExportUsersDataTable

    protected void btn_Excel_Click(object sender, EventArgs e){ExportUsersDataTable()}
    

    The function definition is:

    public void ExportUsersDataTable()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        string sFilename = "UserToRoleMapping.xls";
        HttpResponse response = HttpContext.Current.Response;
        response.Clear();
        response.Charset = ""; //string.Empty;
        response.ContentType = "application/vnd.ms-excel";
        response.AddHeader("Content-Disposition", "attachment;filename=\"" + sFilename + "\"");
        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                GridView gvTemp = new GridView();
    
                //Temporary Table for changing the ExcelSheet Headers
                DataTable dtTemp = new DataTable();
                dtTemp.Columns.Add("User Id");
                dtTemp.Columns.Add("User Name");
                dtTemp.Columns.Add("City");
                dtTemp.Columns.Add("Designation");
                dtTemp.AcceptChanges();
    
                if (ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        DataRow dr = dtTemp.NewRow();
                        dr["User Id"] = ds.Tables[0].Rows[i]["UserId"].ToString();
                        dr["User Name"] = ds.Tables[0].Rows[i]["UserName"].ToString();
                        dr["City"] = ds.Tables[0].Rows[i]["City"].ToString();
                        dr["Designation"] = ds.Tables[0].Rows[i]["Designation"].ToString();
                        dtTemp.Rows.Add(dr);
                        dtTemp.AcceptChanges();
                    }
                }
    
                if (dtTemp.Rows.Count > 0)
                {
                    gvTemp.DataSource = dtTemp;
                    gvTemp.DataBind();
                    gvTemp.RenderControl(htw);
                    response.Write(sw.ToString());
                }
                response.End();
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want display data from database in Listbox...Here is my code, It is not
I use ListView in asp.net. I get data from provider table. According providerId image
I want to use prepared statement to insert and update data in mysqli, Below
i want display 1 record from colums zodys , I'm programint in C# I
I have a statement level trigger that fires whenever INSERT UPDATE or DELETE operations
I'm downloading data from the web that is then showed on a UITableView .
I use CodeIgniter 2.1.0, i want after insert data in database get a message
I have written the code for simple update.I am able to insert and delete
I have a simple quiz application and I want display a nice timer /
I have db with this table (TableToDo): http://goo.gl/NlTEk I want display all records in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.