0

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://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 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

2
  • Why don't you check the sender.GetType() before trying to cast it to something it's not? Commented Sep 29, 2015 at 17:10
  • Set a breakpoint and see that "sender" is really is. Commented Sep 29, 2015 at 17:11

1 Answer 1

1

When you click on the button, the "event" you are handling isn't coming from the CheckBox in your GridView. It's coming from your <button> element.

The way your application is architected, it seems, you have no need of a button -- any time you click on a checkbox to select or unselect it it will perform the action on that single row of data. So it's unclear what you want to happen when the button is pressed.

You could serve both these events in the same method, if you wished to, by at the start of it doing something like:

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
    }
}

But I would suggest having separate event handlers for the separate events.

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't realize when I click the checkbox it will already update the Status of my gridview, I guess no need for an event button. Thank you for an advise sir.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.