mardi 29 septembre 2015

Update database when Button Event is click?

I can't update my database when my checkbox is checked and click the Validate Button. Note:(I use Session to my pass my Data page by page)

In this another code behind page, I add a column checkbox to my gridview.

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

    Session["ValidateSubject"] = SubjectlistTable;

    Response.Redirect("ValidateSubjectTeacher.aspx");

In the ValidateSubjectTeacherPage:

This is the program Aspx:

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

<!DOCTYPE html>

<html xmlns="http://ift.tt/lH0Osb">
<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 Code Behind:

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");
        }
    }
}

The code is working but when I click the submit button, the system prompts me with an error and I can't update my database:

Error message:

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'.

There's something wrong with my checkbox event here:

CheckBox chk = (CheckBox)sender;

It seems that checkbox event and button event can't be simultaneously handled. Please help, this is the only problem I want to fix so that my System is fully working.

Related link Get specific data and update database




Aucun commentaire:

Enregistrer un commentaire