我需要我的代码添加并以asp web形式将数据绑定到gridview

时间:2016-10-14 07:56:45

标签: c# sql asp.net database gridview

我不知道代码有什么问题我试图寻找可能的原因但是还没有弄清楚实际上是什么问题。现在问题是我的网页表单包含一个gridview,其中我放置了一个页脚行,允许用户添加数据,并且数据被添加到数据库并在点击插入链接按钮后被绑定到gridview ,但是当我填充数据时出现问题,当按下链接按钮时,它每次都会在gridview和数据库中添加两次数据.Below是我在gridview上执行CRUD操作的整个代码:



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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Label ID="lblMessage" runat="server" ForeColor="Green" EnableViewState="false" />

        <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
            AutoGenerateColumns="false" Width="100%" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
            OnRowUpdating="GridView1_RowUpdating" DataKeyNames="AutoId" OnRowDeleting="GridView1_RowDeleting" AllowPaging="true"
            PageSize="10" OnPageIndexChanging="GridView1_PageIndexChanging" ShowFooter="True" OnRowCreated="GridView1_RowCreated" OnRowCommand="GridView1_RowCommand">

            <Columns>

                <asp:TemplateField HeaderText="Edit">

                    <ItemTemplate>

                        <asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" />

                    </ItemTemplate>

                    <EditItemTemplate>

                        <asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update" />

                        <asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel" CommandName="Cancel" />

                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:LinkButton ID="lnkBtnInsert" runat="server"
                            CommandName="Insert">Insert</asp:LinkButton>
                    </FooterTemplate>

                </asp:TemplateField>

                <asp:BoundField HeaderText="AutoId" DataField="AutoId" ReadOnly="true" />

                <asp:TemplateField HeaderText="First Name">

                    <ItemTemplate>

                        <%# Eval("FirstNAme") %>
                    </ItemTemplate>
                    <EditItemTemplate>

                        <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName") %>' />

                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    </FooterTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Last Name">

                    <ItemTemplate>

                        <%# Eval("LastName") %>
                    </ItemTemplate>
                    <EditItemTemplate>

                        <asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>' />

                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
                    </FooterTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Age">

                    <ItemTemplate>

                        <%# Eval("Age") %>
                    </ItemTemplate>
                    <EditItemTemplate>

                        <asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age") %>' Columns="3" />

                        <asp:RequiredFieldValidator ID="REw" runat="server" ControlToValidate="txtAge" Text="*" />

                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtlage" runat="server"></asp:TextBox>
                    </FooterTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Is Active?">

                    <ItemTemplate>

                        <%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>
                    </ItemTemplate>

                    <HeaderStyle HorizontalAlign="Left" />

                    <EditItemTemplate>

                        <asp:DropDownList ID="dropActive" runat="server" SelectedValue='<%# Eval("Active") %>'>

                            <asp:ListItem Text="Yes" Value="True" />

                            <asp:ListItem Text="No" Value="False" />

                        </asp:DropDownList>

                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="ddlactive" runat="server">
                            <asp:ListItem Text="Yes" Value="True" Selected="True"></asp:ListItem>
                            <asp:ListItem Text="No" Value="False"></asp:ListItem>
                        </asp:DropDownList>
                    </FooterTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Delete?">

                    <ItemTemplate>

                        <span onclick="return confirm('Are you sure to delete?')">

                            <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete" />

                        </span>

                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

            <AlternatingRowStyle BackColor="White" />

            <EditRowStyle BackColor="#efefef" />

            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

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

            <RowStyle BackColor="#EFF3FB" HorizontalAlign="Center" />

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

            <SortedAscendingCellStyle BackColor="#F5F7FB" />

            <SortedAscendingHeaderStyle BackColor="#6D95E1" />

            <SortedDescendingCellStyle BackColor="#E9EBEF" />

            <SortedDescendingHeaderStyle BackColor="#4870BE" />

        </asp:GridView>
    </form>
</body>
</html>
&#13;
&#13;
&#13;

&#13;
&#13;
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.Configuration;
using System.Data;

namespace WebApplication5
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PopulateData();
            }

        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            this.PopulateData();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            this.PopulateData();
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var autoID = GridView1.DataKeys[e.RowIndex].Value;

            using (SqlConnection conn = new SqlConnection(_connStr))
            {

                string sql = "Delete from PersonalDetail" +

                " where AutoId = @AutoId";

                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {

                    cmd.Parameters.AddWithValue(
                    "@AutoId", autoID);

                    conn.Open();

                    cmd.ExecuteNonQuery();

                    conn.Close();
                }
            }

            lblMessage.Text =
            "Record has been deleted successfully !";

            lblMessage.ForeColor = System.Drawing.
            Color.Red;

            this.PopulateData();
        }

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

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var autoID = GridView1.DataKeys[e.RowIndex].Value;

            GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;

            TextBox tFirstName = row.FindControl("txtFirstName") as TextBox;

            TextBox tLastName = row.FindControl("txtLastName") as TextBox;

            TextBox tAge = row.FindControl("txtAge") as TextBox;

            DropDownList dropActive = row.FindControl("dropActive") as DropDownList;

            using (SqlConnection conn = new SqlConnection(_connStr))
            {

                string sql = "Update PersonalDetail set FirstName = @FirstName,LastName=@LastName, Age= @Age, Active = @Active" + " where AutoId = @AutoId";

                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {

                    cmd.Parameters.AddWithValue(
                    "@FirstName", tFirstName.Text.Trim());

                    cmd.Parameters.AddWithValue(
                    "@LastName", tLastName.Text.Trim());

                    cmd.Parameters.AddWithValue(
                    "@Age", tAge.Text.Trim());

                    cmd.Parameters.AddWithValue(
                    "@Active", dropActive.SelectedValue);

                    cmd.Parameters.AddWithValue(
                    "@AutoId", autoID);

                    conn.Open();

                    cmd.ExecuteNonQuery();

                    conn.Close();
                }
            }

            lblMessage.Text =
            "Record updated successfully !";

            GridView1.EditIndex = -1;

            this.PopulateData();
        }
        private void PopulateData()
        {

            DataTable table = new DataTable();

            using (SqlConnection conn = new SqlConnection(_connStr))
            {

                string sql = "Select * from PersonalDetail";

                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {

                    using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
                    {

                        ad.Fill(table);
                    }
                }
            }

            GridView1.DataSource = table;

            GridView1.DataBind();
        }

        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {

        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Insert"))
            {
                TextBox name = (TextBox)GridView1.FooterRow.FindControl("TextBox1");
                TextBox lname = (TextBox)GridView1.FooterRow.FindControl("txtlname");
                TextBox age = (TextBox)GridView1.FooterRow.FindControl("txtlage");
                DropDownList isactive = (DropDownList)GridView1.FooterRow.FindControl("ddlactive");
                using(SqlConnection conn = new SqlConnection(_connStr))
                {
                    SqlCommand cmd = new SqlCommand("INSERT INTO PersonalDetail(FirstName,LastName,Age,Active) VALUES('" + name.Text + "','" + lname.Text + "','" + age.Text + "','" + isactive.SelectedItem.Value + "')",conn);
                    cmd.CommandType = CommandType.Text;
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    //int result = cmd.ExecuteNonQuery();
                    conn.Close();
                }
            }
            lblMessage.Text =
            "Record has been Added successfully !";
            this.PopulateData();
            
        }
    }

}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

请尝试以下代码:

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        GridView1.RowCommand -= GridView1_RowCommand;
        if (e.CommandName.Equals("Insert"))
        {
            TextBox name = (TextBox)GridView1.FooterRow.FindControl("TextBox1");
            TextBox lname = (TextBox)GridView1.FooterRow.FindControl("txtlname");
            TextBox age = (TextBox)GridView1.FooterRow.FindControl("txtlage");
            DropDownList isactive = (DropDownList)GridView1.FooterRow.FindControl("ddlactive");
            using(SqlConnection conn = new SqlConnection(_connStr))
            {
                SqlCommand cmd = new SqlCommand("INSERT INTO PersonalDetail(FirstName,LastName,Age,Active) VALUES('" + name.Text + "','" + lname.Text + "','" + age.Text + "','" + isactive.SelectedItem.Value + "')",conn);
                cmd.CommandType = CommandType.Text;
                conn.Open();
                cmd.ExecuteNonQuery();
                //int result = cmd.ExecuteNonQuery();
                conn.Close();
            }
        }
        lblMessage.Text =
        "Record has been Added successfully !";
        this.PopulateData();

    }