单击按钮事件时更新数据库?

Update database when Button Event is click?

选中复选框并单击“验证”按钮后,我无法更新数据库。注意:(我使用Session逐页传递我的数据)

在这个页面隐藏的另一个代码中,我向我的 gridview 添加了一个列复选框。

   //Add a colum check row
    SubjectlistTable.Columns.Add("Check", Type.GetType("System.Boolean"));

    Session["ValidateSubject"] = SubjectlistTable;

    Response.Redirect("ValidateSubjectTeacher.aspx");

在 ValidateSubjectTeacherPage 中:

这是程序 ASPX:

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Student Assessment Form</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link rel="stylesheet" href="Bootstrap/css/bootstrap-theme.css" />
    <link rel="stylesheet" href="Bootstrap/css/bootstrap.min.css"/> 
    <link rel="stylesheet" type="text/css" href="Stylesheets/ValidateSubjectTeacherStyle.css"/>

    <!--Side bar link-->
    <link rel="stylesheet" href="SidebarBootstrap/css/bootstrap.min.css" />
    <link rel="stylesheet" href="SidebarBootstrap/css/simple-sidebar.css" />
</head>
<body>
    <form id="form1" runat="server">
        <div class="headerwrapper">
            <div id="headercontent" class="jumbotron">
                <img id="img1" src="usjrlogo.png" />
                <h1 id="title">Online AppSess System</h1>
            </div>
        </div>

        <div class="container" style="text-align: center; margin: 0 auto;">
            <br />
            <h1>Validation of Subjects</h1>
            <br />
            <asp:GridView runat="server" CssClass="table table-hover table-bordered" ID="ValidateSubject" Style="text-align: center"></asp:GridView>
        </div>

        <div style="float: right; padding-right: 75px;">
            <button type="button" runat="server" class="btn btn-primary" onserverclick="ValidateSubject_Click">Validate</button>
            <button type="button" runat="server" class="btn btn-success" onserverclick="GoBackTeacher_Click">Go Back</button>
        </div>
    </form>

    <script src="jquery/jquery.min.js"></script>
    <script src="Bootstrap/js/bootstrap.min.js"></script>
</body>
</html>

Aspx 代码隐藏:

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.Data;

namespace SoftwareAnalysisAndDesign.SAD
{
    public partial class ValidateSubjectTeacher : System.Web.UI.Page
    {
        CheckBox check = new CheckBox();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["ValidateSubject"] == null)
            {
                Response.Redirect("TeacherPage.aspx", true);
            }

            if (!IsPostBack)
            {
                ValidateSubject.DataSource = Session["ValidateSubject"];
                ValidateSubject.DataBind();
            }
            //Add a checkbox in the last row of GridView Progmatically
            foreach (GridViewRow row in ValidateSubject.Rows)
            {
                check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
                check.Enabled = true;
                check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
                check.AutoPostBack = true; //Set the AutoPostBack property to true
            }
        }
        protected void ValidateSubject_Click(object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give row


            string validated = "Validated";
            string notyetvalidated = "Not yet validated";
            string studid = grvRow.Cells[0].Text;
            string coursenum = grvRow.Cells[1].Text;

            if (chk.Checked)
            {
                grvRow.Cells[10].Text = validated;
                //Open Connection
                using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
                {
                    //Open Connection to database
                    try
                    {
                        conn.Open();
                    }
                    catch (Exception E)
                    {
                        Console.WriteLine(E.ToString());
                    }

                    using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = @Validated where StudentID = @studentID and CourseNo = @Coursenumber" ,conn))
                    {
                        cmd.Parameters.AddWithValue("@Validated", validated);
                        cmd.Parameters.AddWithValue("@studentID", studid);
                        cmd.Parameters.AddWithValue("@Coursenumber", coursenum);
                        cmd.ExecuteNonQuery();
                    }

                    //Close Connection to database
                    try
                    {
                        conn.Close();
                    }
                    catch (Exception E)
                    {
                        Console.WriteLine(E.ToString());
                    }
                }

            }
            else
            {
                grvRow.Cells[10].Text = notyetvalidated;
            }
        }
        protected void GoBackTeacher_Click(object sender, EventArgs e)
        {
            Response.Redirect("TeacherPage.aspx");
        }
    }
}

代码可以运行,但是当我点击提交按钮时,系统提示错误,我无法更新我的数据库:

错误信息:

An exception of type 'System.InvalidCastException' occurred in SoftwareAnalysisAndDesign.dll but was not handled in user code Additional information: Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlButton' to type 'System.Web.UI.WebControls.CheckBox'.

我的复选框事件有问题:

CheckBox chk = (CheckBox)sender;

checkbox事件和button事件好像不能同时处理。 请帮忙,这是我唯一要解决的问题,这样我的系统才能正常工作。

相关link

当您单击该按钮时,您正在处理的 "event" 并非来自 GridView 中的 CheckBox。它来自您的 <button> 元素。

您的应用程序的架构方式似乎不需要按钮 - 任何时候您单击 select 或取消 select 复选框时它都会执行操作在那一行数据上。所以不清楚你想要在按下按钮时发生什么。

如果您愿意,您可以在同一方法中为这两个事件提供服务,方法是在开始时执行以下操作:

protected void ValidateSubject_Click(object sender, EventArgs e) {
    if ( sender.GetType().FullName == "System.Web.UI.WebControls.CheckBox" ) {
        // Have what you currently have for checkboxes here
    } else if ( sender.GetType().FullName == "System.Web.UI.HtmlControls.HtmlButton" ) {
        // Do something else for the button, probably involving getting the GridView's rows and iterating through them
    }
}

但我建议为单独的事件设置单独的事件处理程序。