更新gridview行会添加新记录而不是更新行

时间:2014-05-28 11:42:27

标签: c# asp.net gridview

我正在尝试以格式更新gridview外的gridview记录。在编辑按钮单击时,我编写了一个事件,当它触发时,它将行数据发送到表单供用户编辑,当我单击提交/更新按钮时,gridview将其添加为新记录而不是更新原始记录。 知道我错过了什么吗?

以下是使用gridview的设计代码

<%@ Page Title="Add User" Language="C#" AutoEventWireup="true" CodeFile="adduser.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!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></title>
    <link href="style.css" type="text/css" rel="Stylesheet" />
    <script type="text/javascript">
        function confirmDelete() {
            return confirm("Do you want to delete this record?");
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <ajax:ToolkitScriptManager ID="toolkit1" runat="server">
    </ajax:ToolkitScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <table border="0" align="center" cellpadding="2" cellspacing="2" class="maindiv">
                <tr><!--Hidden field for EmployeeID reference-->
                    <td colspan="2"><asp:HiddenField ID="txtHiddenEmpID" Value="0" runat="server" /></td>
                </tr>
                <tr>
                    <td>
                        <span class="asterisk">*</span><asp:Label ID="name" runat="server" Text="Name"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="txtEmpName" runat="server" CssClass="box"></asp:TextBox>
                        <asp:RequiredFieldValidator Display="None" ID="RequiredFieldValidator1" ErrorMessage="Name is required!"
                            EnableClientScript="true" SetFocusOnError="true" runat="server" ControlToValidate="txtEmpName"
                            CssClass="error_msg"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="NameValidator" runat="server" ErrorMessage="Name can not contain numeric or special characters."
                            ControlToValidate="txtEmpName" ValidationExpression="^[A-Za-z ]*$" CssClass="error_msg"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <span class="asterisk">*</span><asp:Label ID="Label1" runat="server" Text="Address"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="addressBox" runat="server" CssClass="box"></asp:TextBox>
                        <asp:RequiredFieldValidator Display="None" ID="AddressValidator" ErrorMessage="Address is required!"
                            EnableClientScript="true" SetFocusOnError="true" runat="server" ControlToValidate="addressBox"
                            CssClass="error_msg"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <span class="asterisk">*</span><asp:Label ID="Label2" runat="server" Text="DOB"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="dobBox" runat="server" CssClass="dob_cal box" ReadOnly="false" ></asp:TextBox>
                        <ajax:CalendarExtender ID="CalenderExtender1" TargetControlID="dobBox" Format="dd/MM/yyyy"
                            runat="server">
                        </ajax:CalendarExtender>
                        <asp:RequiredFieldValidator Display="None" ID="dobValidator" ErrorMessage="DOB is required!"
                            EnableClientScript="true" SetFocusOnError="true" runat="server" ControlToValidate="dobBox"
                            CssClass="error_msg"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <span class="asterisk">*</span><asp:Label ID="Label3" runat="server" Text="Salary"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="salaryBox" runat="server" CssClass="box" MaxLength="8" ></asp:TextBox>
                        <asp:RequiredFieldValidator ID="salaryValidate" runat="server" ControlToValidate="salaryBox"
                            ErrorMessage="Salary is required!" Display="None" CssClass="error_msg" SetFocusOnError="true"
                            EnableClientScript="true"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="SalaryValidator" runat="server" ErrorMessage="Salary can contain only numeric values."
                            Display="None" ControlToValidate="salaryBox" ValidationExpression="^[0-9]*$"
                            CssClass="error_msg"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <span class="asterisk">*</span><asp:Label ID="gender" runat="server" Text="Gender"></asp:Label>
                    </td>
                    <td>
                        <span>
                            <asp:RadioButton GroupName="gendergrp" ID="gendermale" runat="server" Text="Male"
                                Checked="true" /></span><span style="padding-left: 5px;">
                            <asp:RadioButton GroupName="gendergrp" ID="genderfemale" runat="server" Text="Female"
                                        Checked="false" /></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div style="float: right; margin-right: -70px;">
                            <asp:Button ID="Button1" runat="server" CssClass="btn" Text="Save" OnClick="Button1_Click" /></div>
                    </td>
                    <td>
                        <div style="float: left; margin-left: 70px;">
                            <asp:Button ID="CancelBtn" CausesValidation="false" runat="server" CssClass="btn"
                                Text="Cancel" OnClick="CancelBtn_Click" />

                        </div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Label ID="lblError" runat="server" CssClass="error_msg"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:ValidationSummary ID="valSum" DisplayMode="BulletList" EnableClientScript="true"
                            HeaderText="Error!" runat="server" CssClass="error_msg" />
                    </td>
                </tr>
            </table>
            <!--div for data display-->
            <div class="data_display">
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
                    DataKeyNames="EmployeeID" EmptyDataText="There are no data records to display."
                    GridLines="Horizontal" BackColor="#CCCCCC" BorderColor="White" Font-Bold="False"
                    Font-Names="Arial" Font-Size="Medium" ForeColor="#666666" 
                    AllowPaging="True" PageSize="5" PagerSettings-Mode="Numeric" 
                    PagerSettings-Position="Bottom" 
                    onpageindexchanging="GridView1_PageIndexChanging"
                    >
                    <Columns>
<%--                    <asp:TemplateField>
                        <ItemTemplate>
                        <asp:HiddenField ID="EmpID" runat="server" Value='<%# Eval("EmployeeID") %>' />
                        </ItemTemplate>
                    </asp:TemplateField>

--%>                        <asp:BoundField DataField="EmployeeID" HeaderText="Employee ID"  
                            SortExpression="EmployeeID" Visible="true" ItemStyle-HorizontalAlign="Center">
                        <ItemStyle HorizontalAlign="Center" />
                        </asp:BoundField>
                        <asp:BoundField DataField="EmployeeName" HeaderText="Name" SortExpression="EmployeeName"
                            ItemStyle-Width="130px" ItemStyle-HorizontalAlign="Center">
                            <ItemStyle HorizontalAlign="Center" Width="130px" />
                        </asp:BoundField>
                            <asp:BoundField DataField="DateOfBirth" HeaderText="DoB" SortExpression="DateOfBirth"
                            DataFormatString="{0:dd-MM-yyyy}" ItemStyle-Width="100px" ItemStyle-HorizontalAlign="Center">
                            <ItemStyle HorizontalAlign="Center" Width="100px" />
                        </asp:BoundField>
                        <asp:BoundField DataField="Salary" HeaderText="Salary" 
                            SortExpression="Salary">
                            <ItemStyle HorizontalAlign="Center" Width="90px" />
                        </asp:BoundField>
                        <asp:BoundField DataField="Gender" HeaderText="Gender" ItemStyle-Width="90px"
                            ItemStyle-HorizontalAlign="Center">
                            <ItemStyle HorizontalAlign="Center" Width="70px" />
                        </asp:BoundField>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:Button ID="EditBtn" runat="server" Text="Select" CausesValidation="false" OnClick="EditBtn_Click" />
                                <asp:Button  ID="DelBtn" runat="server" Text="Delete" CausesValidation="false" OnClick="DelBtn_Click" OnClientClick="confirmDelete()" />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <EditRowStyle BackColor="#ffffff" />
                    <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="Gray" Font-Bold="false" ForeColor="White" />
                    <PagerStyle BackColor="Gray" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="#E3EAEB" />
                    <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
                    <SortedAscendingCellStyle BackColor="#F8FAFA" />
                    <SortedAscendingHeaderStyle BackColor="#246B61" />
                    <SortedDescendingCellStyle BackColor="#D4DFE1" />
                    <SortedDescendingHeaderStyle BackColor="#15524A" />
                </asp:GridView>
                <br />
                <span style="font-family: Arial; font-size: small; color: Green; font-weight: bold;">
                    You are viewing page <%=GridView1.PageIndex + 1%> of <%=GridView1.PageCount%>
                </span>
            </div>
            <div>
                <asp:Label ID="lblMessage" runat="server"></asp:Label></div>
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>

以下是

背后的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;


public partial class _Default : System.Web.UI.Page
{
    private SqlConnection con;
    private SqlCommand cmd;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            GetData();
        }
    }
    protected void CancelBtn_Click(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            ClearForm();
        }
    }


    protected void CalenderExtender1_DatePick(object sender, EventArgs e)
    {
        dobBox.Text = CalenderExtender1.SelectedDate.ToString();
        CalenderExtender1.Visible = false;
    }

    protected void DatePick(object sender, EventArgs e)
    {
        CalenderExtender1.Visible = true;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {

                string EmpName = txtEmpName.Text;
                string address = addressBox.Text;
                DateTime dob = Convert.ToDateTime(dobBox.Text);
                decimal salary = Convert.ToDecimal(salaryBox.Text);
                bool gender = (gendermale.Checked == true ? true : false);

                string constr = ConfigurationManager.ConnectionStrings["EmpConstr"].ConnectionString;

                con = new SqlConnection();
                con.ConnectionString = constr;

                con.Open();
                int count=0;
                if (txtHiddenEmpID.Value != "") //insert
                {
                    string query = "Insert into Employee (EmployeeName,Address,DateOfBirth,Salary,Gender) Values(@enm,@address,@dob,@salary,@gender)";

                    cmd = new SqlCommand(query, con);

                    cmd.Parameters.AddWithValue("@enm", EmpName);
                    cmd.Parameters.AddWithValue("@address", address);
                    cmd.Parameters.AddWithValue("@dob", dob);
                    cmd.Parameters.AddWithValue("@salary", salary);
                    cmd.Parameters.AddWithValue("@gender", gender);


                    count = cmd.ExecuteNonQuery();
                }
                else
                {
                    // update

                }


                if (count == 1)
                {
                    ClearForm();
                }

                con.Close();
                GetData();

        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }
    #region Public Functions
    public void ClearForm()
    {

        txtEmpName.Text = string.Empty;
        addressBox.Text = string.Empty;
        dobBox.Text = string.Empty;
        salaryBox.Text = string.Empty;
        lblError.Text = string.Empty;
        if (genderfemale.Checked)
        {
            genderfemale.Checked = false;
            gendermale.Checked = true;
        }
        else 
        {
            gendermale.Checked = true;
        }
    }

    private void GetData()
    {
        DataTable dt = new DataTable();
        string constr = ConfigurationManager.ConnectionStrings["EmpConstr"].ConnectionString;

        con = new SqlConnection();
        con.ConnectionString = constr;

        con.Open();

        string query = "SELECT * from Employee Order by EmployeeID DESC";
        SqlDataAdapter sqladpt = new SqlDataAdapter(query, con);
        sqladpt.Fill(dt);

        GridView1.DataSource = dt;
        GridView1.DataBind();
        con.Close();


    }
    #endregion

    #region GridView Functions
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[4].Text == "True")
            {
                e.Row.Cells[4].Text = "Male";
            }
            else
            {
                e.Row.Cells[4].Text = "Female";

            }
        }
    }
    #endregion

    //select data to display when gridview select button is clicked
    //source: www.aspdotnet-suresh.com/2011/01/how-to-delete-records-in-gridview-with.html


    protected void EditBtn_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;

        //Get the row that contains this button
        GridViewRow gvr = (GridViewRow)btn.NamingContainer;
        int index = gvr.RowIndex;
        string ID = GridView1.Rows[index].Cells[0].Text;

        string constr = ConfigurationManager.ConnectionStrings["EmpConstr"].ConnectionString;
        SqlConnection con = new SqlConnection();
        string strSQL = "SELECT * from Employee where employeeid = " + Convert.ToInt32(ID);
        SqlDataAdapter sqlAdpt = new SqlDataAdapter(strSQL,constr);
        DataTable dt = new DataTable();

        sqlAdpt.Fill(dt);

        txtHiddenEmpID.Value = ID;
        txtEmpName.Text = dt.Rows[0]["EmployeeName"].ToString();
        addressBox.Text = dt.Rows[0]["Address"].ToString();
        dobBox.Text =  Convert.ToDateTime(dt.Rows[0]["DateOfBirth"].ToString()).ToString("dd/MM/yyyy");
        salaryBox.Text = dt.Rows[0]["Salary"].ToString();
        string gender = dt.Rows[0]["Gender"].ToString();
        if (gender == "Male")
        {
            gendermale.Checked = true;
            genderfemale.Checked = false;
        }
        else
        {
            gendermale.Checked = false;
            genderfemale.Checked = true; 
        }
        GetData();
    }

    //Delete record from Gridview
    public string date { get; set; }
    protected void DelBtn_Click(object sender, EventArgs e)
    {

        LinkButton lnkbtn = sender as LinkButton;
        //getting particular row linkbutton
        GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
        //getting userid of particular row
        int EmpID = Convert.ToInt32(GridView1.DataKeys[gvrow.RowIndex].Value.ToString());
        string username = gvrow.Cells[0].Text;
        con.Open();
        SqlCommand cmd = new SqlCommand("Delete from Employee where EmployeeID=" + EmpID, con);
        int result = cmd.ExecuteNonQuery();
        con.Close();
        if (result == 1)
        {
            GetData();
            //Displaying alert message after successfully deletion of user
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + username + " details deleted successfully')", true);
        }
        GetData();
    }

    public string Constr { get; set; }


    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GetData();
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataBind();
    }

}

2 个答案:

答案 0 :(得分:1)

你必须为它添加一个简单的查询,

IF EXISTS (SELECT column_name FROM this_table WHERE  some_col = '1' ) 
UPDATE this_table SET column_name='2'  WHERE  column_name = '1' 
ELSE 
INSERT into this_table (column_name) values (4)

答案 1 :(得分:1)

尝试使用sql查询将以下代码更新到表

string query = "update Employee set EmployeeName=@enm,Address=@address, DateOfBirth= 
 @dob, Salary=@salary,Gender=@gender where EmployeeID=@EmpID" 

                cmd = new SqlCommand(query, con);
                cmd.Parameters.AddWithValue("@EmpID", EmpID);
                cmd.Parameters.AddWithValue("@enm", EmpName);
                cmd.Parameters.AddWithValue("@address", address);
                cmd.Parameters.AddWithValue("@dob", dob);
                cmd.Parameters.AddWithValue("@salary", salary);
                cmd.Parameters.AddWithValue("@gender", gender);


                count = cmd.ExecuteNonQuery();

这对您有何帮助。