在GridView中插入/更新

时间:2013-12-07 09:00:14

标签: c# asp.net sql-server-2008 gridview

我正在使用带有C#和SQL server 2008 r2的asp.net。我有Gridview来插入,更新和删除员工的一些数据。

我有两个问题:

  1. 插入时出现此错误

    System.NullReferenceException:未将对象引用设置为对象的实例。

  2. 当我点击编辑时,没有任何事情发生。我认为是因为e.CommandName == "EditRow"中的索引,但我不确定。如果e.CommandName == "UpdateRow"

  3. ,我相信我会遇到同样的问题

    删除工作正常。

    代码。 ASPX

                <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="HR_System_v1.WebForm3" %>
                <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
                </asp:Content>
                <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    
    
                    <p>
                        &nbsp;Enter Employee #<asp:TextBox ID="txtEmpNo" runat="server" 
                            ontextchanged="txtEmpNo_TextChanged"></asp:TextBox>
                        </p>
                    <p>
                        <asp:GridView ID="GridView1" runat="server" DataKeyNames="EmpNo,Qid" 
                            BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" 
                            CellPadding="3" CellSpacing="2" ShowFooter="True"  AutoGenerateColumns="False" CssClass="grid"
                            OnRowCommand="GridView1_RowCommand">
                            <Columns>
                               <asp:TemplateField >
                                    <EditItemTemplate>
                                        <asp:LinkButton ID="lbUpdate" runat="server" CommandArgument='<%# Eval("Qid") %>' CommandName="UpdateRow">Update</asp:LinkButton>
                                        <asp:LinkButton ID="lbCancel" runat="server" CommandArgument='<%# Eval("EmpNo") %>' CommandName="CancelUpdate">Cancel</asp:LinkButton>
                                    </EditItemTemplate>
                                    <ItemTemplate>
                                         <asp:LinkButton ID="lbEdit" runat="server" CommandArgument='<%# Eval("Qid") %>'  CommandName="EditRow">Edit</asp:LinkButton>
                                        <asp:LinkButton ID="lbdelete" runat="server" CommandArgument='<%# Eval("Qid") %>' CommandName="DeleteRow">Delete</asp:LinkButton>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="EmpNo" SortExpression="EmpNo">
                                    <EditItemTemplate>
                                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("EmpNo") %>'></asp:Label>
                                    </EditItemTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("EmpNo") %>'></asp:Label>
                                    </ItemTemplate>
                                    <FooterTemplate>
                                    <asp:LinkButton ID= "lbInsert" runat="server" CommandName="Insert" ValidationGroup="INSERT">Insert</asp:LinkButton>
                                    </FooterTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="QName" SortExpression="QName">
                                    <EditItemTemplate>
                                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("QName") %>'></asp:TextBox>
                                        <asp:RequiredFieldValidator ID="rfvEditQName" ValidationGroup="Update" runat="server"
                                    ControlToValidate="TextBox1" ErrorMessage="Please Enter QName" 
                                    ForeColor="Red">*</asp:RequiredFieldValidator>
                                    </EditItemTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("QName") %>'></asp:Label>
                                    </ItemTemplate>
                                    <FooterTemplate>
                                        <asp:TextBox ID="txtQName" runat="server"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="rfvInsertQName" runat="server"
                                    ControlToValidate="txtQName" ValidationGroup="INSERT" ErrorMessage="Please Enter QName" 
                                    ForeColor="Red">*</asp:RequiredFieldValidator>
                                    </FooterTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="QIssPlace" SortExpression="QIssPlace">
                                    <EditItemTemplate>
                                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("QIssPlace") %>'></asp:TextBox>
                                         <asp:RequiredFieldValidator ID="rfvEditQIssP" ValidationGroup="Update" runat="server"
                                    ControlToValidate="TextBox2" ErrorMessage="Please Enter QIssPlace" 
                                    ForeColor="Red">*</asp:RequiredFieldValidator>
                                    </EditItemTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("QIssPlace") %>'></asp:Label>
                                    </ItemTemplate>
                                    <FooterTemplate>
                                        <asp:TextBox ID="txtQIssP" runat="server"></asp:TextBox>
                                         <asp:RequiredFieldValidator ID="rfvInsertQIssP" runat="server"
                                        ControlToValidate="txtQIssP" ValidationGroup="INSERT" ErrorMessage="Please Enter QIssPlace" 
                                        ForeColor="Red">*</asp:RequiredFieldValidator>
                                    </FooterTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Field" SortExpression="Field">
                                    <EditItemTemplate>
                                        <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Field") %>'></asp:TextBox>
                                        <asp:RequiredFieldValidator ID="rfvEditeField" ValidationGroup="Update" runat="server"
                                        ControlToValidate="TextBox3" ErrorMessage="Please Enter Field" 
                                        ForeColor="Red">*</asp:RequiredFieldValidator>
                                    </EditItemTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="Label4" runat="server" Text='<%# Bind("Field") %>'></asp:Label>
                                    </ItemTemplate>
                                    <FooterTemplate>
                                        <asp:TextBox ID="txtField" runat="server"></asp:TextBox>
                                        <asp:RequiredFieldValidator ID="rfvInsertField" runat="server"
                                        ControlToValidate="txtField" ValidationGroup="INSERT" ErrorMessage="Please Enter Field" 
                                        ForeColor="Red">*</asp:RequiredFieldValidator>
                                    </FooterTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="GradDate" SortExpression="GradDate">
                                    <EditItemTemplate>
                                        <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("GradDate") %>'></asp:TextBox>
                                        <asp:RequiredFieldValidator ID="rfvEditeGradD" ValidationGroup="Update" runat="server"
                                        ControlToValidate="TextBox4" ErrorMessage="Please Enter GradDate" 
                                        ForeColor="Red">*</asp:RequiredFieldValidator>
                                    </EditItemTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="Label5" runat="server" Text='<%# Bind("GradDate") %>'></asp:Label>
                                    </ItemTemplate>
                                    <FooterTemplate>
                                        <asp:TextBox ID="txtGradD" runat="server"></asp:TextBox>
                                        <asp:RequiredFieldValidator ID="rfvInsertGradD" runat="server"
                                        ControlToValidate="txtGradD" ValidationGroup="INSERT" ErrorMessage="Please Enter GradDate" 
                                        ForeColor="Red">*</asp:RequiredFieldValidator>
                                    </FooterTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="QStatus" SortExpression="QStatus">
                                    <EditItemTemplate>
                                        <asp:DropDownList ID="DropDownList1" runat="server" SelectedValue = '<%# Bind("QStatus") %>'>
                                        <asp:ListItem Value = " "> اختر</asp:ListItem>
                                        <asp:ListItem Value= "مصدقه من وزاره التربيه والتعليم في بلد التخرج">مصدقه من وزاره التربيه والتعليم في بلد التخرج</asp:ListItem>
                                        <asp:ListItem Value = "مصدقه من وزارة الخارجيه في بلد التخرج">مصدقه من وزارة الخارجيه في بلد التخرج</asp:ListItem>
                                        <asp:ListItem Value= "مصدقه من السفاره السعوديه في بلد التخرج" >مصدقه من السفاره السعوديه في بلد التخرج</asp:ListItem>
                                        <asp:ListItem Value= " مصدقه من الملحقيه الثقافية السعوديه في بلد التخرج" >مصدقه من الملحقيه الثقافية السعوديه في بلد التخرج</asp:ListItem>
                                        <asp:ListItem Value = "مصدقه من الخارجية السعودية في جده">مصدقه من الخارجية السعودية في جده</asp:ListItem>
                                        <asp:ListItem Value = "غير مصدقه">غير مصدقه</asp:ListItem>
                                        </asp:DropDownList>
                                        <asp:RequiredFieldValidator ID="rfvInsertQStaus" ValidationGroup="Update" runat="server"
                                        ControlToValidate="DropDownList1" ErrorMessage="Please Select QStatus" 
                                        ForeColor="Red" InitialValue = "اختر">*</asp:RequiredFieldValidator>
                                    </EditItemTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="Label6" runat="server" Text='<%# Bind("QStatus") %>'></asp:Label>
                                    </ItemTemplate>
                                    <FooterTemplate>
                                    <asp:DropDownList ID="ddlQStatus" runat="server" >
                                        <asp:ListItem Value = " "> اختر</asp:ListItem>
                                        <asp:ListItem Value= "مصدقه من وزاره التربيه والتعليم في بلد التخرج">مصدقه من وزاره التربيه والتعليم في بلد التخرج</asp:ListItem>
                                        <asp:ListItem Value = "مصدقه من وزارة الخارجيه في بلد التخرج">مصدقه من وزارة الخارجيه في بلد التخرج</asp:ListItem>
                                        <asp:ListItem Value= "مصدقه من السفاره السعوديه في بلد التخرج" >مصدقه من السفاره السعوديه في بلد التخرج</asp:ListItem>
                                        <asp:ListItem Value= " مصدقه من الملحقيه الثقافية السعوديه في بلد التخرج" >مصدقه من الملحقيه الثقافية السعوديه في بلد التخرج</asp:ListItem>
                                        <asp:ListItem Value = "مصدقه من الخارجية السعودية في جده">مصدقه من الخارجية السعودية في جده</asp:ListItem>
                                        <asp:ListItem Value = "غير مصدقه">غير مصدقه</asp:ListItem>
                                        </asp:DropDownList>
                                        <asp:RequiredFieldValidator ID="rfvInsertQStatus" runat="server"
                                        ControlToValidate="ddlQStatus" ValidationGroup="INSERT" ErrorMessage="Please Select QStatus" 
                                        ForeColor="Red">*</asp:RequiredFieldValidator>
                                    </FooterTemplate>
                                </asp:TemplateField>
                            </Columns>
                            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
                            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
                            <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
                            <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
                            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
                            <SortedAscendingCellStyle BackColor="#FFF1D4" />
                            <SortedAscendingHeaderStyle BackColor="#B95C30" />
                            <SortedDescendingCellStyle BackColor="#F1E5CE" />
                            <SortedDescendingHeaderStyle BackColor="#93451F" />
                        </asp:GridView>
                        </p>
                    <p>
                        &nbsp;</p>
                    <p>
                        &nbsp;</p>
                    <p>
                        &nbsp;</p>
                    <p>
                        &nbsp;</p>
                    <p>
                        &nbsp;</p>
    
                                <br />
                    <br />
                    <br />
    
                                &nbsp;<p>
                            &nbsp;<asp:ValidationSummary ID="ValidationSummary1" ValidationGroup="INSERT" ForeColor="Red" runat="server" />
                            <asp:ValidationSummary ID="ValidationSummary2" ForeColor="Red" runat="server" />
                        <p>
                            &nbsp;</p>
                                &nbsp;</asp:Content>
    

    c#c​​ode

                using System;
                using System.Configuration;
                using System.Data;
                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.Data.SqlClient;
    
                namespace HR_System_v1
                {
                    public partial class WebForm3 : System.Web.UI.Page
                    {
                        string connStr = "Data Source=ICAD-PROJ-SOFT\\SQLEXPRESS;Initial Catalog=dbHrSys;Integrated Security=True";
                        SqlDataAdapter sqlda = new SqlDataAdapter();
                        SqlCommand com = new SqlCommand();
                        DataTable dt;
    
                        protected void Page_Load(object sender, EventArgs e)
                        {
                            if (!IsPostBack)
                            {
                                bindgrid();
                            }
                        }
                        private void bindgrid()
                        {
                            SqlConnection conn = new SqlConnection(connStr);
                            dt = new DataTable();
                            com.Connection = conn;
                            com.CommandText = "SELECT * FROM Quali";
                            sqlda = new SqlDataAdapter(com);
                            sqlda.Fill(dt);
                            GridView1.DataSource = dt;
                            GridView1.DataBind();
                        }
    
                        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
                        {
                            if (e.CommandName == "Insert")
                            {
                                TextBox txtEmpNo = (TextBox)GridView1.FooterRow.FindControl("txtEmpNo");
                                TextBox txtName = (TextBox)GridView1.FooterRow.FindControl("txtQName");
                                TextBox txtIssp = (TextBox)GridView1.FooterRow.FindControl("txtQIssP");
                                TextBox txtfield = (TextBox)GridView1.FooterRow.FindControl("txtField");
                                TextBox txtGrad = (TextBox)GridView1.FooterRow.FindControl("txtGradD");
                                string txtStatus = ((DropDownList)GridView1.FooterRow.FindControl("ddlQStatus")).SelectedValue;
    
    
                                SqlConnection conn = new SqlConnection(connStr);
                                com.Connection = conn;
                                com.CommandText = "INSERT INTO Quali (EmpNo, QName, QIssPlace, Field, GradDate,QStatus) Values ('" + txtEmpNo.Text + "','" + txtName.Text + "','" + txtIssp .Text + "','" + txtfield.Text + "','" + txtGrad.Text + "',@status)";
                                com.Parameters.AddWithValue("@status", txtStatus );
                                conn.Open();
                                com.ExecuteNonQuery();
                                Response.Write("Record inserted successfully");
                                bindgrid();
                                conn.Close(); 
    
                            }
    
                            else if (e.CommandName == "UpdateRow")
                            {
    
                                GridViewRow rowSelect = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer);
                                int rowindex = rowSelect.RowIndex;
    
                                TextBox txtEmpNo = (TextBox)GridView1.Rows[rowindex].FindControl("txtEmpNo");
                                TextBox txtName = (TextBox)GridView1.Rows[rowindex].FindControl("TextBox1");
                                TextBox txtIssp = (TextBox)GridView1.Rows[rowindex].FindControl("TextBox2");
                                TextBox txtfield = (TextBox)GridView1.Rows[rowindex].FindControl("TextBox3");
                                TextBox txtGrad = (TextBox)GridView1.Rows[rowindex].FindControl("TextBox4");
                                string txtStatus = ((DropDownList)GridView1.Rows[rowindex].FindControl("DropDownList1")).SelectedValue;
    
                                SqlConnection conn = new SqlConnection(connStr);
                                com.Connection = conn;
                                com.CommandText = "Update Quali Set QName = '" + txtName.Text + "', QIssPlace='" + txtIssp .Text + "', Field='" + txtfield.Text + "',GradDate='" + txtGrad.Text + "', QStatus = @status Where EmpNo = @Empnum)";
                                com.Parameters.AddWithValue("@status", txtStatus );
                                com.Parameters.AddWithValue("@Empnum", txtEmpNo );
                                conn.Open();
                                com.ExecuteNonQuery();
                                Response.Write("Record updated successfully");
                                GridView1.EditIndex = -1;
                                bindgrid();
                                conn.Close(); 
    
                            }
    
                            else if (e.CommandName == "CancelUpdate")
                            {
                                GridView1.EditIndex = -1;
                                bindgrid();
                            }
    
                            else if (e.CommandName == "EditRow")
                            {
                                GridViewRow rowSelect = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer);
                                int rowindex = rowSelect.RowIndex;
                                bindgrid();
                            }
    
                            else if (e.CommandName == "DeleteRow")
                            {
                                int qID = Convert.ToInt16(e.CommandArgument);
                                SqlConnection conn = new SqlConnection(connStr);
                                com.Connection = conn;
                                com.CommandText = "Delete from Quali where Qid = @qID";
                                com.Parameters.AddWithValue("@qID", qID );
                                conn.Open();
                                com.ExecuteNonQuery();
                                Response.Write("Record deleted successfully");
                                bindgrid();
                                conn.Close();
                            }
                        }
                    }
                }
    

2 个答案:

答案 0 :(得分:0)

要在编辑模式下制作gridview,您需要添加事件划船

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
 GridView1.EditIndex = e.NewEditIndex;
 bindgrid(); // your GV bind function
}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
   GridView1.EditIndex = -1;
   bindgrid();// your GV bind function
} 

答案 1 :(得分:0)

code in .aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Customer.aspx.cs" Inherits="Customer.Customer" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</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" 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">
<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" Text="Edit" 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:TextBox ID="txtusername" 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"/>

</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<EditItemTemplate>
<asp:TextBox ID="txtDesg" runat="server" Text='<%#Eval("Designation") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDesg" 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>
</asp:GridView>
</div>
<div>
<asp:Label ID="lblresult" runat="server"></asp:Label>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
</div>
</form>
</body>
</html>


c# code


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

namespace Customer
{
    public partial class Customer : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(@"Data Source=PRASHANTH1\SQLSERVER2012;Integrated Security=true;Initial Catalog=emp");
        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 txtusername = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtusername");
            TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtcity");
            TextBox txtDesignation = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtDesg");
            con.Open();
            SqlCommand cmd = new SqlCommand("update Employee_Details set City='" + txtcity.Text + "',Designation='" + txtDesignation.Text + "',UserName='" + txtusername.Text + "'  where UserId=" + userid, con);
            cmd.ExecuteNonQuery();
            con.Close();
            lblresult.ForeColor = Color.Green;
            lblresult.Text = txtusername.Text  + " 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.Red;
                lblresult.Text = username + " details deleted successfully";
            }
        }
        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.Green;
                    lblresult.Text = txtUsrname.Text + " Details inserted successfully";
                }
                else
                {
                    lblresult.ForeColor = Color.Red;
                    lblresult.Text = txtUsrname.Text + " Details not inserted";
                }
            }
        }
    }
}