使用复选框在数据库中插入或删除行

时间:2017-12-12 15:47:05

标签: c# asp.net checkbox

我正在尝试更新DataList中的单个记录。我选择了DataList类型,以便我可以在同一页面上有一个包含许多记录的水平行,可以使用该页面从预先确定的人员列表中进行考勤,但我想在我去的时候更新。我将使用志愿者参加,并且不想强迫用户在完成后点击保存(他们可能会分心而忘记这样做)。因此,每个复选框都标记出现在的人。或者取消选中标记它们不存在。

这是我的CSHTML页面:

      <%@ 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" RowNumber='<%# Eval("RowNumber") %>' AttendanceID='<%# Eval("AttendanceID") %>' PeopleId='<%# Eval("PeopleID") %>' Text='<%# Eval("CheckBoxPresent") %>' Checked='<%# Eval("CheckBoxPresent").ToString().Equals("1") %>' CssClass="ChkBoxClass" OnCheckedChanged="CheckBoxPresent_CheckedChanged" AutoPostBack="true"  />
  <asp:Label ID="RowNumber" runat="server" Text='<%# Eval("RowNumber") %>'  />                   
 <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>

这是我的CS页面:

    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)
        {

        }
    }
}

这只是我正在使用我的存储过程添加或删除的按钮代码。

    protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
        {
            //start of checkbox
            CheckBox ChkBxPresent = sender as CheckBox;
            Boolean ChkBxPresentState = ChkBxPresent.Checked;
            // I added this to try to compare to to get a specific row for Insert
            string BoxIndex = ChkBxPresent.Attributes["RowNumber"];

            //DataList1.DataBind();

            foreach (DataListItem itm in DataList1.Items)
            {


                // I added this to try to compare to within the Item List
                string ItmIndex = ((Label)itm.FindControl("RowNumber")).Text; 


                if (itm.ItemType == ListItemType.Item)
                {
                // Let's gather the parameter data needed
                    string strPeopleID = ChkBxPresent.Attributes["PeopleId"];
                    string strAttendanceID = ChkBxPresent.Attributes["AttendanceID"];
                    string strCheckBoxPresent = ChkBxPresent.Attributes["IsChecked"];
                    string strAttGroupID = ((Label)itm.FindControl("SoCID")).Text;
                    string strAttendanceDate = ((Label)itm.FindControl("AttendanceDate")).Text;

                    // Here is what we do if the box is checked...

                    // I used this to try and compare the values.  It showed the one I wanted to 
                    // compare to but the ItmIndex only returned odd rows.  So I don't match somtimes

                    //Response.Write("BoxIdx=");
                    //Response.Write(BoxIndex);
                    //Response.Write("and  ItmIdx=");
                    //Response.Write(ItmIndex);


                    // I added the compare of ItmIndex == BoxIndex but it was not consistent.  Again it was only returning odd
                    // numbers and no even numbers to compare to for some reason.

                    if (ChkBxPresentState == true)
                    {
                        string strAction = "ADD";


                        //Response.Write("Add BoxIdx=");
                        //Response.Write(BoxIndex);
                        //Response.Write("and  ItmIdx=");
                        //Response.Write(ItmIndex);



                        SqlConnection con = new SqlConnection(strcon);

                        //Response.Write("Let's Insert it...");
                        //Response.Write("PeopleID");
                        //Response.Write(strPeopleID);
                        //Response.Write("ChurchID");
                        //Response.Write(strChurchID);
                        //Response.Write("GroupID");
                        //Response.Write(strAttGroupID);
                        //Response.Write("AttDate");
                        //Response.Write(strAttendanceDate);
                        //Response.Write("Action");
                        //Response.Write(strAction);
                        //Response.End();

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


                        cmdInsertData.Parameters.Add(new SqlParameter("@AttGroupID", SqlDbType.Int));
                        cmdInsertData.Parameters.Add(new SqlParameter("@Action", SqlDbType.VarChar));
                        cmdInsertData.Parameters.Add(new SqlParameter("@PeopleID", SqlDbType.Int));
                        cmdInsertData.Parameters.Add(new SqlParameter("@ChurchID", SqlDbType.Int));
                        cmdInsertData.Parameters.Add(new SqlParameter("@AttendanceDate", SqlDbType.DateTime));



                        // Convert Strings to Int where needed 
                        if (Int32.TryParse(strAttGroupID.ToString(), out int intGroupID)) { }
                        if (Int32.TryParse(strPeopleID.ToString(), out int intPeopleID)) { }
                        if (Int32.TryParse(strChurchID.ToString(), out int intChurchID)) { }



                        //Response.Write(intAttendanceID);
                        //Response.Write("-");
                        //Response.Write(strAction);
                        //Response.End();

                        cmdInsertData.Parameters["@AttGroupID"].Value = intGroupID;
                        cmdInsertData.Parameters["@Action"].Value = strAction;
                        cmdInsertData.Parameters["@PeopleID"].Value = intPeopleID;
                        cmdInsertData.Parameters["@ChurchID"].Value = intChurchID;
                        cmdInsertData.Parameters["@AttendanceDate"].Value = strAttendanceDate;


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

                    }
                else
                {
                        string strAction = "DEL";

                        //Response.Write("DEL BoxIdx=");
                        //Response.Write(BoxIndex);
                        //Response.Write("and  ItmIdx=");
                        //Response.Write(ItmIndex);
                        //Response.Write(" |");

                        // Here is what we do if the Box is unchecked       
                        //Response.Write("Let's Remove it...");
                        //Response.Write(strPeopleID);
                        //Response.Write("aID");
                        //Response.Write(strAttendanceID);
                        //Response.Write("checkBoxPresent:");
                        //Response.Write(strCheckBoxPresent);
                        //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("@AttendanceID", SqlDbType.Int));
                cmdDelete.Parameters.Add(new SqlParameter("@Action", SqlDbType.VarChar));


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



                        //Response.Write(intAttendanceID);
                        //Response.Write("-");
                        //Response.Write(strAction);
                        //Response.End();

                        cmdDelete.Parameters["@AttendanceID"].Value = intAttendanceID;
                        cmdDelete.Parameters["@Action"].Value = strAction;


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

                        // End delete data

                    }
                }

        }
//end of checkbox 

        }

它显然不完整,因为我只是想让它显示正确的数据。我对删除部分进行了测试(如果未选中该框),并且它没有删除特定记录,因为EventArgs返回所有复选框值。如果我将其更改为DataListItemEventArgs,则会返回特定的行,但我会在检查时失去复选框的功能。我想我需要分开这些,但我不知道如何完成这项任务。

以下是我要使用的功能: 1.设置日期并检索任何出勤情况。

Image of form that loads the AttendanceTaker

我要使用大型复选框访问的页面示例,以便在平板电脑上使用。

Sample of AttendanceTaker page

我使用选定答案中的想法重写了代码。这是最终工作的代码。

      // Checkbox Checked?
    protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
    {

        CheckBox ChkBxPresent = sender as CheckBox;
        Boolean ChkBxPresentState = ChkBxPresent.Checked;

        if (Int32.TryParse(ChkBxPresent.Attributes["AttendanceID"].ToString(), out int intAttendanceID)) { }


        // Let's gather the parameter data needed
        string strPeopleID = ChkBxPresent.Attributes["PeopleId"];
        string strAttendanceID = ChkBxPresent.Attributes["AttendanceID"];
        string strCheckBoxPresent = ChkBxPresent.Attributes["IsChecked"];
        string strAttGroupID = ChkBxPresent.Attributes["SoCID"];
        string strAttendanceDate = ChkBxPresent.Attributes["AttendanceDate"];




        if (intAttendanceID == 0)  // Add Attendance Record it does not exist and was checked
        {
            string strAction = "ADD";

            SqlConnection con = new SqlConnection(strcon);

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

            cmdInsertData.Parameters.Add(new SqlParameter("@AttGroupID", SqlDbType.Int));
            cmdInsertData.Parameters.Add(new SqlParameter("@Action", SqlDbType.VarChar));
            cmdInsertData.Parameters.Add(new SqlParameter("@PeopleID", SqlDbType.Int));
            cmdInsertData.Parameters.Add(new SqlParameter("@ChurchID", SqlDbType.Int));
            cmdInsertData.Parameters.Add(new SqlParameter("@AttendanceDate", SqlDbType.DateTime));


            // Convert Strings to Int where needed 
            if (Int32.TryParse(strAttGroupID.ToString(), out int intGroupID)) { }
            if (Int32.TryParse(strPeopleID.ToString(), out int intPeopleID)) { }
            if (Int32.TryParse(strChurchID.ToString(), out int intChurchID)) { }


            cmdInsertData.Parameters["@AttGroupID"].Value = intGroupID;
            cmdInsertData.Parameters["@Action"].Value = strAction;
            cmdInsertData.Parameters["@PeopleID"].Value = intPeopleID;
            cmdInsertData.Parameters["@ChurchID"].Value = intChurchID;
            cmdInsertData.Parameters["@AttendanceDate"].Value = strAttendanceDate;


            con.Open();
            cmdInsertData.ExecuteNonQuery();
            con.Close();
            DataList1.DataBind();

        }
        else  // Delete Attendance Record it was unchecked
        {
            string strAction = "DEL";

            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("@AttendanceID", SqlDbType.Int));
            cmdDelete.Parameters.Add(new SqlParameter("@Action", SqlDbType.VarChar));


            cmdDelete.Parameters["@AttendanceID"].Value = intAttendanceID;
            cmdDelete.Parameters["@Action"].Value = strAction;


            con.Open();
            cmdDelete.ExecuteNonQuery();
            con.Close();
            DataList1.DataBind();
            // End delete data

        }

    ////end of checkbox 

1 个答案:

答案 0 :(得分:0)

您可以将复选框中的PeopleId(和/或attendanceID)的值作为属性传递,并避免迭代DataList。

您的复选框

<asp:CheckBox ID="CheckBoxPresent" runat="server" PeopleId='<%# Eval("PeopleID") %>' Text='<%# Eval("CheckBoxPresent") %>' Checked='<%# Eval("CheckBoxPresent").ToString().Equals("1") %>' CssClass="ChkBoxClass" OnCheckedChanged="CheckBoxPresent_CheckedChanged" AutoPostBack="true"  />

背后的代码

string strPeopleID = ChkBxPresent.Attributes["PeopleId"];

然后,如果已选中,则仅对该ID发出insert命令,如果未选中,则发出该ID的删除命令。