GridView点击更新按钮未更新数据反而加载全量数据问题求助
问题描述
数据检索功能可正常运行,但点击GridView的更新按钮时,并未更新当前GridView中的数据,反而会从数据库中加载全部数据并显示。
相关代码
AssignmentAttendance.aspx.cs 代码
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Web.Services.Description; namespace Lab06 { public partial class AssignmentAttendance : System.Web.UI.Page { Student sStudent = new Student(); Attendance aAttendance = new Attendance(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { bind(); } } protected void bind() { List<Student> acclist = new List<Student>(); acclist = sStudent.getAccountAll(); GridView1.DataSource = acclist; GridView1.DataBind(); } protected void Retrieve_Attendance_Click(object sender, EventArgs e) { string _connStr = ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString; SqlConnection SQLConn = new SqlConnection(_connStr); /* string username = Session["User"].ToString();*/ SqlCommand cmd = new SqlCommand("SELECT * FROM Student WHERE ClassCode = @ClassCode", SQLConn); SQLConn.Open(); cmd.Parameters.AddWithValue("@ClassCode", tb_classcode.Text); cmd.ExecuteNonQuery(); SQLConn.Close(); SqlDataAdapter SQLAdapter = new SqlDataAdapter(cmd); DataTable DT = new DataTable(); SQLAdapter.Fill(DT); GridView1.DataSource = DT; GridView1.DataBind(); } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { int result = 0; Student stud = new Student(); string categoryID = GridView1.DataKeys[e.RowIndex].Value.ToString(); result = stud.AccountDelete(categoryID); if (result > 0) { Response.Write("<script>alert('Student Remove successfully');</script>"); } else { Response.Write("<script>alert('Student Removal NOT successfully');</script>"); } Response.Redirect("AssignmentAttendance.aspx"); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; bind(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; bind(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { int result = 0; Student stud = new Student(); GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex]; string tStudent_ID = ((TextBox)row.Cells[0].Controls[0]).Text; string tClassCode = ((TextBox)row.Cells[3].Controls[0]).Text; result = stud.AttendanceUpdate(tClassCode, tStudent_ID); /*if (result > 0) { Response.Write("<script>alert('Product updated successfully');</script>"); } else { Response.Write("<script>alert('Product NOT updated');</script>"); }*/ GridView1.EditIndex = -1; bind(); } } }
AssignmentAttendance.aspx 代码
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="AssignmentAttendance.aspx.cs" Inherits="Lab06.AssignmentAttendance" %> <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <p> Attendance</p> <p> Filter Search</p> <p> Class code <asp:TextBox ID="tb_classcode" runat="server"></asp:TextBox> </p> <p> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Height="168px" Width="1451px" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"> <Columns> <asp:BoundField AccessibleHeaderText="Joe" DataField="Student_ID" HeaderText="Student_ID" /> <asp:BoundField AccessibleHeaderText="Joe" DataField="Name" HeaderText="Name" /> <asp:BoundField AccessibleHeaderText="Joe" DataField="Pass" HeaderText="Pass" /> <asp:BoundField DataField="ClassCode" HeaderText="ClassCode" /> <asp:CommandField AccessibleHeaderText="Joe" ShowDeleteButton="True" ShowEditButton="True" /> </Columns> </asp:GridView> </p> <asp:Button ID="Retrieve_Attendance" runat="server" Text="Confirm" style="float:right;" OnClick="Retrieve_Attendance_Click" /> </asp:Content>
问题原因
- 更新后绑定的数据源错误:点击更新按钮后,
GridView1_RowUpdating方法最后调用了bind(),而bind()方法默认是调用sStudent.getAccountAll()加载数据库中全部学生数据,并非之前筛选出的指定班级数据。 - 筛选状态未持久化:通过
Retrieve_Attendance_Click筛选出指定班级的学生后,没有保存当前的筛选条件(即tb_classcode中的班级代码)。更新操作触发页面回发后,重新绑定数据时无法复用之前的筛选条件,导致回到加载全部数据的初始状态。 - 检索方法存在冗余代码:
Retrieve_Attendance_Click中调用了cmd.ExecuteNonQuery(),该方法用于执行增删改操作,此处是查询操作,完全不需要这个调用;同时手动打开关闭数据库连接也是多余的,SqlDataAdapter会自动管理连接的打开和关闭。
修复方案
核心思路:持久化筛选条件,复用筛选逻辑
步骤1:修改bind()方法,根据筛选条件动态绑定数据
将筛选的班级代码存储在ViewState中,bind()方法判断是否存在筛选条件,存在则加载对应班级的数据,否则加载全部数据:
protected void bind() { if (!string.IsNullOrEmpty(ViewState["ClassCode"]?.ToString())) { // 加载筛选后的班级数据 string classCode = ViewState["ClassCode"].ToString(); string _connStr = ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString; SqlCommand cmd = new SqlCommand("SELECT * FROM Student WHERE ClassCode = @ClassCode", new SqlConnection(_connStr)); cmd.Parameters.AddWithValue("@ClassCode", classCode); SqlDataAdapter SQLAdapter = new SqlDataAdapter(cmd); DataTable DT = new DataTable(); SQLAdapter.Fill(DT); GridView1.DataSource = DT; } else { // 加载全部学生数据 List<Student> acclist = sStudent.getAccountAll(); GridView1.DataSource = acclist; } GridView1.DataBind(); }
步骤2:修改检索按钮方法,保存筛选条件到ViewState
在点击确认筛选时,把班级代码存入ViewState,确保回发后能保留筛选状态:
protected void Retrieve_Attendance_Click(object sender, EventArgs e) { string classCode = tb_classcode.Text.Trim(); // 保存筛选条件到ViewState ViewState["ClassCode"] = classCode; string _connStr = ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString; SqlCommand cmd = new SqlCommand("SELECT * FROM Student WHERE ClassCode = @ClassCode", new SqlConnection(_connStr)); cmd.Parameters.AddWithValue("@ClassCode", classCode); SqlDataAdapter SQLAdapter = new SqlDataAdapter(cmd); DataTable DT = new DataTable(); SQLAdapter.Fill(DT); GridView1.DataSource = DT; GridView1.DataBind(); }
步骤3:清理检索方法中的冗余代码
删除Retrieve_Attendance_Click中多余的SQLConn.Open()、cmd.ExecuteNonQuery()和SQLConn.Close(),让SqlDataAdapter自动管理连接。
完成以上修改后,更新、编辑取消等操作触发的bind()调用,都会根据ViewState中保存的筛选条件加载对应班级的数据,不会再回到全部数据的状态。
内容的提问来源于stack exchange,提问作者Ian Wong
相关产品推荐
相关产品推荐

