【问题标题】:Use Checkbox to Insert or Delete a row in Database使用复选框在数据库中插入或删除行
【发布时间】:2017-12-13 06:23:05
【问题描述】:

我正在尝试更新 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 

【问题讨论】:

    标签: c# asp.net checkbox


    【解决方案1】:

    您可以将复选框中的 PeopleId(和/或出席 ID)的值作为属性传递,避免遍历 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 发出插入命令,如果未选中,则针对该 ID 发出删除命令。

    【讨论】:

    • Sea Charp,这让我走上了正确的道路!现在我不只是得到列表的第一个 id。非常感谢您花时间阅读文字墙并提出我想要完成的内容。 :)
    • 我还有一个问题。我在删除时传递了 AttendanceRecord ID,所以我只删除了那一行。但是当我插入时,我会在 DataList 中插入尽可能多的没有复选框的行。有没有办法将特定复选框的 id 隔离为仅插入 1 行。
    • 我不明白。您可以编辑原始问题以包含您修改后的代码吗?
    • 好的。我对其进行了编辑以包括我所做的更改。谢谢。
    • 再次感谢 Sea Charp,在您的帮助下,我走上了正确的道路。
    猜你喜欢
    • 1970-01-01
    • 2021-10-05
    • 2012-02-10
    • 1970-01-01
    • 2012-04-11
    • 2017-11-26
    • 2018-03-09
    • 2014-05-27
    • 2012-09-05
    相关资源
    最近更新 更多