1

I'm new to C# and I don't think I have good grasp on how to write to a database yet. I'm not sure how to write checkboxes to a specific column in a database. If you can see an area I need to specifically study, please let me know. It's hard to know what I need to know in trying to teach myself how to do things like this. Thank you for your help.

If you need any further information, just let me know.

Goal: My goal is to write the Checkbox selections to a table in a database. Each checkbox has a column in a table, and I just want a 'Y' to be populated if something is checked and nothing populated if it's not checked. The titles of the columns are the same as the checkbox labels.

Problem: I'm not sure how to get the data from the checkboxlist, into the database.

DB Structure:

enter image description here

Website draft sample:

enter image description here

HTML:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Revocations.Default_2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="Styles/StyleSheet1.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
        <div class="t_row_header">
            <asp:Image ID="imgLogo" runat="server" CssClass="logo" ImageUrl="~/Images/logo.png" />
        </div>
        <h1>Transfer Revocations</h1>
        <div class="form-fields">

            <div class="form-group-left">
                <label>
                    <asp:RequiredFieldValidator ID="rqvldSchoolYear" runat="server" ControlToValidate="txtSchoolYear" CssClass="ErrorMessage" ErrorMessage="Please enter a school   year."   SetFocusOnError="True">*</asp:RequiredFieldValidator>
                    School Year:
                    <asp:CompareValidator ID="cmpvldSchoolYear" runat="server" ControlToValidate="txtSchoolYear" CssClass="ErrorMessage" ErrorMessage="Please enter a school year  &gt;=    2017." Operator="GreaterThanEqual" SetFocusOnError="True" ValueToCompare="2017">*</asp:CompareValidator>
                </label>
                &nbsp;<asp:TextBox ID="txtSchoolYear" runat="server" CssClass="txtBox"></asp:TextBox>

                <label>
                    <asp:RequiredFieldValidator ID="rqvldStudentID" runat="server" ControlToValidate="txtStudentID" CssClass="ErrorMessage" ErrorMessage="Please enter a student ID."     SetFocusOnError="True">*</asp:RequiredFieldValidator>
                    Student ID:</label>&nbsp;<asp:TextBox ID="txtStudentID" runat="server" CssClass="txtBox"></asp:TextBox>

                <label>
                    <asp:RequiredFieldValidator ID="rqvldFirstName" runat="server" ControlToValidate="txtFirstName" CssClass="ErrorMessage" ErrorMessage="Please enter a first name."     SetFocusOnError="True">*</asp:RequiredFieldValidator>
                    First Name:</label>&nbsp;<asp:TextBox ID="txtFirstName" runat="server" CssClass="txtBox"></asp:TextBox>

                <label>
                    <asp:RequiredFieldValidator ID="rqvldLastName" runat="server" ControlToValidate="txtLastName" CssClass="ErrorMessage" ErrorMessage="Please enter a last name"     SetFocusOnError="True">*</asp:RequiredFieldValidator>
                    Last Name:</label>&nbsp;<asp:TextBox ID="txtLastName" runat="server" CssClass="txtBox"></asp:TextBox>

                <label>
                    <asp:RequiredFieldValidator ID="rqvldRevokedSchool" runat="server" ControlToValidate="txtRevokedSchool" CssClass="ErrorMessage" ErrorMessage="Please enter the     revoking school" SetFocusOnError="True">*</asp:RequiredFieldValidator>
                    Revoked School:</label>&nbsp;<asp:TextBox ID="txtRevokedSchool" runat="server" CssClass="txtBox"></asp:TextBox>

                <label>
                    <asp:RequiredFieldValidator ID="rqvldRevocationDate" runat="server" ControlToValidate="txtRevocationDate" CssClass="ErrorMessage" ErrorMessage="Please enter a     revocation date" SetFocusOnError="True">*</asp:RequiredFieldValidator>
                    Revocation Date:</label>&nbsp;<asp:TextBox ID="txtRevocationDate" runat="server" TextMode="Date" CssClass="txtBox"></asp:TextBox>

            </div>
            <!-- form-group-left -->

            <div class="form-group-right">
                <label>
                    Reason:<asp:CheckBoxList ID="chkbxlst1" runat="server">
                        <asp:ListItem text="Academics"  Value="1"></asp:ListItem>
                        <asp:ListItem text="Attendance" Value="2"></asp:ListItem>
                        <asp:ListItem text="Behavior"  Value ="3"></asp:ListItem>
                        <asp:ListItem text="Cooperative Relationship" Value="4"></asp:ListItem>
                    </asp:CheckBoxList>
                    <br />
                </label>
                <label>
                    <asp:RequiredFieldValidator ID="rqvldNotes" runat="server" ControlToValidate="txtNotes" CssClass="ErrorMessage" ErrorMessage="Please enter a note."     SetFocusOnError="True">*</asp:RequiredFieldValidator>
                    Notes:</label>&nbsp;&nbsp;<asp:TextBox ID="txtNotes" runat="server" height="218px" TextMode="MultiLine" CssClass="InsideShadow"></asp:TextBox>
                <br />
                <asp:Button ID="btnSubmit" runat="server" Text="SUBMIT" CssClass="btn" OnClick="btnSubmit_Click" />
            </div>

        </div>
        <asp:ValidationSummary ID="ValidationSummary1" runat="server" CssClass="ErrorMessage" />


        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:PPSS_RevocationConnection %>" DeleteCommand="SELECT 
       [SchoolYear]
      ,[Student_ID]
      ,[Last_Name]
      ,[First_Name]
      ,[Revoked_School]
      ,CAST([Revocation_Date] AS DATE) AS [Revocation_Date]
      ,[Notes]
      ,[Academics]
      ,[Attendance]
      ,[Behavior]
      ,[Cooperative Relationship]

  FROM [PPSS_Work].[Transfers].[Revocations]"
            SelectCommand="SELECT 
       [SchoolYear]
      ,[Student_ID]
      ,[Last_Name]
      ,[First_Name]
      ,[Revoked_School]
      ,CAST([Revocation_Date] AS DATE) AS [Revocation_Date]
      ,[Notes]
      ,[Academics]
      ,[Attendance]
      ,[Behavior]
      ,[Cooperative Relationship]

  FROM [PPSS_Work].[Transfers].[Revocations]"
            UpdateCommand="SELECT 
       [SchoolYear]
      ,[Student_ID]
      ,[Last_Name]
      ,[First_Name]
      ,[Revoked_School]
      ,CAST([Revocation_Date] AS DATE) AS [Revocation_Date]
      ,[Notes]
      ,[Academics]
      ,[Attendance]
      ,[Behavior]
      ,[Cooperative Relationship]

  FROM [PPSS_Work].[Transfers].[Revocations]"></asp:SqlDataSource>
    </form>
</body>
</html>

C#:

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


namespace Revocations
{
    public partial class Default_2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            // Establish SQL Connection

            SqlConnection sqlCon = new SqlConnection("Data Source = acctsql; Initial Catalog = PPSS_Work; Integrated Security = True");
            {
                // Write INSERT SQL statement
                SqlCommand sqlCom = new SqlCommand("INSERT INTO [PPSS_Work].[Transfers].[t_Revocations](SchoolYear, Student_ID, Last_Name, First_Name,    Revoked_School,Revocation_Date,  Academics, Attendance, Behavior, Cooperative Relationship, Notes) VALUES(@SchoolYear, @Student_ID, @First_Name, @Last_Name,    @Revoked_School,  @Revocation_Date,@Academics, @Attendance, @Behavior, @Cooperative Relationship, @Notes)", sqlCon);

                sqlCom.Parameters.AddWithValue("@SchoolYear", txtSchoolYear.Text);
                sqlCom.Parameters.AddWithValue("@Student_ID", txtStudentID.Text);
                sqlCom.Parameters.AddWithValue("@First_Name", txtFirstName.Text);
                sqlCom.Parameters.AddWithValue("@Last_Name", txtLastName.Text);
                sqlCom.Parameters.AddWithValue("@Revoked_School", txtRevokedSchool.Text);
                sqlCom.Parameters.AddWithValue("@Revocation_Date", txtRevocationDate.Text);
                sqlCom.Parameters.AddWithValue("@Notes", txtNotes.Text);


                sqlCom.Parameters.AddWithValue("@Academics", txtNotes.Text);
                sqlCom.Parameters.AddWithValue("@Attendance", txtNotes.Text);
                sqlCom.Parameters.AddWithValue("@Behavior", txtNotes.Text);
                sqlCom.Parameters.AddWithValue("@[Cooperative Relationship]", txtNotes.Text);

                sqlCon.Open();
                sqlCom.ExecuteNonQuery();
                sqlCon.Close();

                if (IsPostBack)
                {
                    txtSchoolYear.Text = "";
                    txtStudentID.Text = "";
                    txtFirstName.Text = "";
                    txtLastName.Text = "";
                    txtRevokedSchool.Text = "";
                    txtRevocationDate.Text = "";
                    chkbxlst1.Text = "";
                    txtNotes.Text = "";
                }
            }
        }

    }
}
JM1
  • 1,595
  • 5
  • 19
  • 41
  • 1
    What exactly are you trying to write to the database? I don't see any attempt to get values from `chkbxlst1` or put those values into that query. What would such an `INSERT` look like if you wrote it manually with hard-coded values? – David Dec 13 '17 at 15:20
  • https://www.google.co.uk/search?q=ASP.NET+get+selected+items+in+checkboxlist&oq=ASP.NET+get+selected+items+in+checkboxlist&aqs=chrome..69i57j0l4.5357j0j7&sourceid=chrome&ie=UTF-8 - plenty of examples of how to get all the checked boxes. It's not a new problem. Then you just have to include the relevant fields in your INSERT query and set each field's input parameter true/false depending on whether the relevant checkbox was selected or not. – ADyson Dec 13 '17 at 15:22
  • @David, that's where I'm lost, I'm not sure what that would look like. – JM1 Dec 13 '17 at 15:23
  • 1
    "I'm not sure how to get the data from the checkboxlist, into the database." That process contains multiple steps. First, you have to know what checkboxes are checked. Next, you have to know how the tables for storing this data in the database are designed, or, if they aren't yet designed, you have to understand how this data will be used by the rest of the system in order to design them. Lastly, you have to know how to write (and later, how to read) data to/from the database to and from the form your application uses. Good job not letting us know where your problem lies. –  Dec 13 '17 at 15:23
  • 1
    @JM1: Well, *we* certainly don't know what your database looks like or what data you want to insert into it. Start at the beginning. What is the structure of your database? What data do you want to be there after invoking an `INSERT` operation? – David Dec 13 '17 at 15:24
  • @David, I've added a screenshot of the DB structure, I can drop those columns and create new ones of a different type if needed. – JM1 Dec 13 '17 at 15:28
  • @Will. Thank you for laying out the steps for me, this is helpful. On my first web development project, it's difficult to know what the problem is enough to spell it out for people trying to help. I hope I didn't frustrate you, I appreciate the help. – JM1 Dec 13 '17 at 15:29
  • @JM1: That screen shot doesn't tell us what you're *expecting* to happen. Every column in that screen shot is already accounted for in your `INSERT` operation except for `RevocationID`. Is that the column you want to insert your checkbox list values into? What would the result of that look like? That column is just an `int`, what should happen if multiple checkboxes are selected? Please clarify what it is you're actually trying to do. – David Dec 13 '17 at 15:32
  • @David, I added a screenshot of the draft DB. If someone checks 'Academics', I want a 'Y" to show up in the Academics column of my database. If they check all of them, then I want a 'Y" in all of the columns. Does this make sense? – JM1 Dec 13 '17 at 15:36
  • 2
    @JM1: Ah, now we're getting somewhere. Take a look at the `.Items` property on your `chkbxlst1` object. Also take a look at some of the code samples here: https://stackoverflow.com/q/18924147/328193 I'd *recommend* using `bit` columns for true boolean values instead of `"Y"` or `"N"` in `varchar(50)` columns. (Why 50 characters if you only expect 1?) But essentially you should be able to examine the `.Items` and see which ones are "selected". From there you can set the values in your SQL command parameters. – David Dec 13 '17 at 15:40
  • Thank you @David! I will do as you suggest. I also need to get better and giving what's needed in the initial ask of my question. It's hard to know what's needed as I'm new to C# and writing to the DB from a site. I appreciate the help, and your patience. – JM1 Dec 13 '17 at 15:45
  • @n8wrl, What do you mean 'using' statements. I can see them in the first answer on https://stackoverflow.com/questions/20042952/an-exception-of-type-system-data-sqlclient-sqlexception-occurred-in-system-dat, but I'm not sure why or how to use them. – JM1 Dec 13 '17 at 16:35
  • @JM1 glad you asked! Very important: https://stackoverflow.com/questions/212198/what-is-the-c-sharp-using-block-and-why-should-i-use-it – n8wrl Dec 14 '17 at 15:23

1 Answers1

3

The problem is that you don't have the code to write the data into the database.

You need to iterate through items in chkbxlst1 and set the proper parameters:

foreach(ListItem item in chkbxlst1.Items)
{
    if(item.Checked)
        sqlCom.Parameters.AddWithValue("@"+item.Text, "Y");
}

Remarks:

  1. Do not use Y/N for your columns. Change the columns to use BIT type.
  2. I used a cast to ListItem in foreach because I'm not sure what is the type of Items property of your CheckBoxList.
RePierre
  • 9,358
  • 2
  • 20
  • 37
  • Thanks @RePierre. If I change the columns' to a bit type, how would that change the loop? – JM1 Dec 13 '17 at 15:59