mardi 12 décembre 2017

c# .net Use Checkbox to Insert or Delete a row in Database

I have used this site extensively to find great help but this is my first time to ask a question. My knowledge with code is limited. I am usually able to find some examples and plug them in and make them work. But I have reached a roadblock that requires more help. So thanks for understanding... My issue is that I am trying to update a single record in a DataList. I have chosen the DataList so that I can have a horizontal row with many records on the same page. I am using this page to take attendance from a pre-determined list of people. But, I want to update as I go. I will be using volunteers to take attendance and want to not have to have them save after they are finished. They may get distracted and forgot to do so. So, each check box marks a person present. Or unchecking marks them absent.

Here is my asp page:

    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master"  AutoEventWireup="true" CodeBehind="AttendanceTaking.aspx.cs" Inherits="AtChurch.AttendanceTaking" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <style>.ChkBoxClass input {width:25px; height:25px;}
    .auto-style1 {
        width: 32px;
    }
    .auto-style2 {
        width: 183px;
    }
</style>
    <table>
        <tr>
            <td class="auto-style2"><strong>Take Attendance</strong></td>
            <td class="auto-style1">Date:</td>
            <td>
                <strong>
                <asp:Label ID="lblAttendanceDate" runat="server"></asp:Label>
                </strong>
            </td>
            <td>
                Attendance Group:</td>
            <td>
                <strong>
                <asp:Label ID="lblAttendanceGroup" runat="server" ></asp:Label>
                </strong>
            </td>
        </tr>
        </table>
    <p>
        <asp:HiddenField ID="HiddenAttendanceDate" runat="server" />
        <asp:HiddenField ID="HiddenSoCID" runat="server" />
    </p>
    <p>
        <asp:DataList RepeatDirection="Horizontal" RepeatColumns="6" ID="DataList1" runat="server" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="DataList1_SelectedIndexChanged" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Both">
            <FooterStyle BackColor="White" ForeColor="#000066" />
            <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
            <ItemStyle ForeColor="#000066" />
            <ItemTemplate>
                <asp:CheckBox ID="CheckBoxPresent" runat="server" Text='<%# Eval("CheckBoxPresent") %>' Checked='<%# Eval("CheckBoxPresent").ToString().Equals("1") %>' CssClass="ChkBoxClass" OnCheckedChanged="CheckBoxPresent_CheckedChanged" AutoPostBack="true"  />
                <asp:Label ID="FullName" runat="server" Text='<%# Eval("FullName") %>'  />
                 <asp:Label ID="PeopleID" runat="server" Text='<%# Eval("PeopleID") %>'  />
                <asp:Label ID="AttendanceID" runat="server" Text='<%# Eval("AttendanceID") %>' ></asp:Label>
                <asp:Label ID="AttendLabel" runat="server" Text="&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"></asp:Label> <br />
<br />
            </ItemTemplate>
            <SelectedItemStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
            <FooterTemplate>
                :
            </FooterTemplate>
        </asp:DataList>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AtChurchConString %>" SelectCommand="sp_AttendanceTaking" SelectCommandType="StoredProcedure">
            <SelectParameters>
                <asp:ControlParameter ControlID="ChurchID" DefaultValue="0" Name="ChurchID" PropertyName="Value" />
                <asp:ControlParameter ControlID="HiddenSoCID" DefaultValue="0" Name="HiddenSoCID" PropertyName="Value" />
                <asp:Parameter DefaultValue="1" Name="Select" Type="Int32" />
                <asp:ControlParameter ControlID="HiddenAttendanceDate" DefaultValue="" Name="AttendanceDate" PropertyName="Value" Type="DateTime" />
                <%--<asp:ControlParameter ControlID="CheckBoxPresent" DefaultValue="0" Name="CheckBoxPresent" PropertyName="Value" />--%>
               <%-- <asp:ControlParameter ControlID="AttendanceID" DefaultValue="0" Name="AttendanceID" PropertyName="Value" />--%>
                <%--<asp:ControlParameter ControlID="PeopleID" DefaultValue="0" Name="PeopleID" PropertyName="Value" />--%>
            </SelectParameters>
        </asp:SqlDataSource>

        <asp:HiddenField ID="ChurchID" runat="server" />



    </p>
    <p>
        &nbsp;</p>
    </asp:Content>

And here is my cs page:

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

namespace AtChurch
{
    public partial class AttendanceTaking : System.Web.UI.Page

    {
        private static string strcon = WebConfigurationManager.ConnectionStrings["AtChurchConString"].ConnectionString;



        // Need these for Security
        public string strRole, strChurchID, strAttGroup, strAttDate;
        public bool ValidUser { get; private set; }




        // Checkbox Checked?
        protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
        {
            //start of checkbox
            CheckBox ChkBxPresent = sender as CheckBox;
            Boolean ChkBxPresentState = ChkBxPresent.Checked;


            //DataList1.DataBind();

            foreach (DataListItem itm in DataList1.Items)
            {


                if (itm.ItemType == ListItemType.Item )
                {
                    string strPeopleID = ((Label)itm.FindControl("PeopleID")).Text;
                    string strAttendanceID = ((Label)itm.FindControl("AttendanceID")).Text;


                    Response.Write(strPeopleID);
                    Response.End();

                    //string strAttID = "";
                    //strAttID = ((DataBoundLiteralControl)item.Controls[1]).Text;


                    if (ChkBxPresentState == true)
                {
                    Response.Write("Let's Insert it...");
                    Response.Write(strPeopleID); 

                    Response.End();
                }
                else
                {
                //Response.Write("Let's Remove it...");
                //Response.End();

                SqlConnection con = new SqlConnection(strcon);
                // First let's delete this Groups Data

                SqlCommand cmdDelete = new SqlCommand("sp_AttendanceTaking", con);
                cmdDelete.CommandType = CommandType.StoredProcedure;

                //cmdDelete.Parameters.Add(new SqlParameter("@HiddenSoCID", SqlDbType.Int));
                cmdDelete.Parameters.Add(new SqlParameter("@AttendanceID", SqlDbType.Int));
                //cmdDelete.Parameters.Add(new SqlParameter("@ChurchID", SqlDbType.Int));
                //cmdDelete.Parameters.Add(new SqlParameter("@AttendanceDate", SqlDbType.DateTime));
                cmdDelete.Parameters.Add(new SqlParameter("@CheckBoxPresent", SqlDbType.Int));
                        //cmdDelete.Parameters.Add(new SqlParameter("@PeopleID", SqlDbType.Int));


                        // Convert Strings to Int where needed 
                        if (Int32.TryParse(strAttendanceID.ToString(), out int intAttendanceID)) { }



                        Response.Write(intAttendanceID);
                        Response.Write("-");
                        Response.Write(1);
                        Response.End();

                        cmdDelete.Parameters["@AttendanceID"].Value = intAttendanceID;
                        cmdDelete.Parameters["@CheckBoxPresent"].Value = 0;


                con.Open();
                cmdDelete.ExecuteNonQuery();
                con.Close();

                        // End delete data

                    }
                }

        }
//end of checkbox 

        }





        protected void Page_Load(object sender, EventArgs e)

        {
            SqlConnection con = new SqlConnection(strcon);

            if (!IsPostBack)
            {


                // Get Attendance Group ID from the Attendance page.

                //if (Request.QueryString["SoCID"].ToString() != null && Request.QueryString["SoCID"].ToString() != null)
                string SoCID = Server.UrlDecode(Request.QueryString["SoCID"]);
                string AttendanceDate = Server.UrlDecode(Request.QueryString["AttendanceDate"]);
               // Response.Write("ok?"+AttendanceDate);
               // Response.End();

                if (SoCID != null && AttendanceDate != null)
                {
                    strAttGroup = SoCID;
                    HiddenSoCID.Value = strAttGroup;
                    lblAttendanceGroup.Text = strAttGroup;

                    strAttDate = AttendanceDate;
                    HiddenAttendanceDate.Value = strAttDate;
                    lblAttendanceDate.Text = strAttDate;


                    //strAttDate =  Request.QueryString["AttendanceDate"].ToString();

                    //Response.Write(strAttGroup);
                    //Response.Write(strAttDate);
                    //Response.End();

                }

                else
                {
                    //Response.Write("error");

                    Response.Redirect("Attendance.aspx");
                    Response.End();
                }

            }


            // Security Start
            if (Session["Role"] is null && Session["ChurchID"] is null)
            {
                Response.Redirect("Login.aspx");
                return;
            }


            if (Session["Role"] != null && Session["ChurchID"] != null)
            {
                if (!string.IsNullOrEmpty(Session["Role"].ToString()))
                {
                    strRole = Session["Role"].ToString();
                    strChurchID = Session["ChurchID"].ToString();
                }
            }

            if (strRole == ("SuperAdmin") || strRole == ("ChurchAdmin"))
            {
                ValidUser = true;
            }

            if (ValidUser != true)
            {
                Response.Redirect("Login.aspx");
            }
            // Security End

            //Populate the ChurchID for Insert
            ChurchID.Value = strChurchID;
        }

            protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void Button_AttendanceTaker_Command(object sender, CommandEventArgs e)
        {

        }
    }
}

It is obviously not complete. As I am just trying to get it to show the right data. I did a test of the delete portion (When the box is unchecked) and it did not delete a specific record because the EventArgs returns all the checkbox values. If I change it to DataListItemEventArgs it returns specific rows but then I lose the functionality of the checkbox on check. I am thinking I need to separate these but I am not sure how to accomplish this.

Here is the functionality I am going for: 1. Setup the date and retrieve any attendance if already taken.

Image of form that loads the AttendanceTaker

And a sample of the page I am going for with a large checkbox so it can be used on a tablet.

Sample of AttendanceTaker page

Any help is appreciated.




Aucun commentaire:

Enregistrer un commentaire