GridView中的“编辑”按钮无效

时间:2015-11-19 06:51:42

标签: c# asp.net gridview

我的页面首先显示事件的下拉菜单。用户从此下拉菜单中选择一个事件,然后单击一个按钮。单击按钮后,GridView将填充相应的数据。一切正常。

然后,当用户查看此数据时,有两个可用的按钮:编辑和删除。单击编辑应该允许用户在那里编辑行。然后编辑按钮变为更新按钮,然后他们将单击以更新行。这是不起作用的区域。

现在,在用户点击编辑之前,一切都很好。当他们单击编辑时,程序会崩溃或清除GridView。我知道我的代码有问题...我认为它与BindGrid()有关(参见我的C#)。任何人都可以帮我这个吗?

<%@ Page Title="" Language="C#" MasterPageFile="~/admin/admin.master" AutoEventWireup="true" CodeFile="copycopyviewregistrant.aspx.cs" Inherits="admin_Default5" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    Choose event:
    <asp:DropDownList ID="DropDownListEvent" runat="server">
    </asp:DropDownList>
    <asp:Button ID="ButtonChangeEvent" runat="server" 
        onclick="ButtonChangeEvent_Click" Text="Button" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="RegistrantId"
OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" 
        EmptyDataText="No records has been added." CellPadding="4" ForeColor="#333333" 
        GridLines="None" AllowPaging="True" 
        OnPageIndexChanging="PagingRegistrant_PageIndexChanging" AllowSorting="True">
    <AlternatingRowStyle BackColor="White" />
<Columns>
    <asp:TemplateField HeaderText="First Name" ItemStyle-Width="80">
        <ItemTemplate>
            <asp:Label ID="lblFirstName" runat="server" Text='<%# Eval("FirstName") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName") %>'></asp:TextBox>
        </EditItemTemplate>

<ItemStyle Width="150px"></ItemStyle>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Last Name" ItemStyle-Width="80">
        <ItemTemplate>
            <asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LastName") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>'></asp:TextBox>
        </EditItemTemplate>

        <ItemStyle Width="150px"></ItemStyle>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Address Line 1" ItemStyle-Width="80">
        <ItemTemplate>
            <asp:Label ID="lblAddressLine1" runat="server" Text='<%# Eval("AddressLine1") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtAddressLine1" runat="server" Text='<%# Eval("AddressLine1") %>'></asp:TextBox>
        </EditItemTemplate>

<ItemStyle Width="150px"></ItemStyle>
    </asp:TemplateField>
    <asp:CommandField ButtonType="Link" ShowEditButton="true" 
        ShowDeleteButton="true" ItemStyle-Width="150">
<ItemStyle Width="150px"></ItemStyle>
    </asp:CommandField>
</Columns>
    <EditRowStyle BackColor="#2461BF" />
    <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" />
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#F5F7FB" />
    <SortedAscendingHeaderStyle BackColor="#6D95E1" />
    <SortedDescendingCellStyle BackColor="#E9EBEF" />
    <SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</asp:Content>

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;


public partial class admin_Default5 : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!this.IsPostBack)
        {
            string events = DropDownListEvent.SelectedValue;

            using (SqlConnection sqlConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
            {
                sqlConn2.Open();

                using (SqlCommand sqlCmd2 = new SqlCommand())
                {
                    sqlCmd2.Connection = sqlConn2;
                    sqlCmd2.CommandType = System.Data.CommandType.Text;

                    sqlCmd2.CommandType = System.Data.CommandType.StoredProcedure;
                    sqlCmd2.CommandText = "spGetAllEvents";

                    sqlCmd2.ExecuteNonQuery();

                    SqlDataReader sqlReader = sqlCmd2.ExecuteReader();

                    if (sqlReader.HasRows)
                    {
                        DropDownListEvent.DataSource = sqlReader;
                        DropDownListEvent.DataTextField = "EventName";
                        DropDownListEvent.DataValueField = "EventId";
                        DropDownListEvent.DataBind();
                    }

                    sqlConn2.Close();
                }

            }

        }
    }
    private void BindGrid()
    {
        string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("spRegistrantsGridView"))
            {
                cmd.CommandType = CommandType.StoredProcedure;  
                cmd.Parameters.AddWithValue("@Action", "SELECT");
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                        this.BindGrid();
                    }
                }
            }


        }
    }

    //Edit Button
    protected void OnRowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        this.BindGrid();
    }

    //Update Button
    protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = GridView1.Rows[e.RowIndex];
        int registrantId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
        string firstName = (row.FindControl("txtFirstName") as TextBox).Text;
        string lastName = (row.FindControl("txtLastName") as TextBox).Text;
        string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("spRegistrantsGridView"))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Action", "UPDATE");
                cmd.Parameters.AddWithValue("@RegistrantId", registrantId);
                cmd.Parameters.AddWithValue("@FirstName", firstName);
                cmd.Parameters.AddWithValue("@LastName", lastName);
                //cmd.Parameters.AddWithValue("@AddressLine1", addressLine1);
                //cmd.Parameters.AddWithValue("@AddressLine2", addressLine2);
                //cmd.Parameters.AddWithValue("@City", city);
                //cmd.Parameters.AddWithValue("@State", state);
                //cmd.Parameters.AddWithValue("@Zip", zip);
                //cmd.Parameters.AddWithValue("@Country", country);


                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
        GridView1.EditIndex = -1;
        this.BindGrid();
    }

    //Cancel Edit Button
    protected void OnRowCancelingEdit(object sender, EventArgs e)
    {
        GridView1.EditIndex = -1;
        this.BindGrid();
    }

    //Delete Button
    protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int registrantId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
        string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("spRegistrantsGridView"))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Action", "DELETE");
                cmd.Parameters.AddWithValue("@RegistrantId", registrantId);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
        this.BindGrid();
    }

    //JavaScript confirm delete
    //protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    //{
    //    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
    //    {
    //        (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
    //    }
    //}

    protected void PagingRegistrant_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
       GridView1.PageIndex = e.NewPageIndex; 
        DataBind();
    }
    protected void ButtonChangeEvent_Click(object sender, EventArgs e)
    {
        string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("spRegistrantsGridView"))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Action", "SELECT");
                cmd.Parameters.Add("@EventId", SqlDbType.Int).Value = DropDownListEvent.SelectedValue;
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                    }
                }
            }
        }
    }
}

0 个答案:

没有答案