Imports System.Data
Imports AppVariable
Imports AppCommon
Imports System.Data.SqlClient
Imports System.Data.Common

Partial Class Answer
    Inherits System.Web.UI.Page

#Region "********************** メンバ変数 **********************"

    Private originalDataTable As DataTable 'VW回答一括更新用
    Private originalDataTableAll As DataTable 'VW回答全体一括更新用
    Private _user As LoginUser
    Private questionVisibilityParameters As Dictionary(Of String, Boolean)
    Private Const S_Answer_ClientMessage As String = "S_Answer_ClientMessage"

#End Region

#Region "******************** ページイベント ********************"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If IsPostBack Then
            'LV回答全体の表示非表示情報を復元
            Dim visibilitySettings = TryCast(ViewState("ItemVisibility"), Dictionary(Of String, Boolean))
            If visibilitySettings IsNot Nothing Then
                For Each visiblitySetting As KeyValuePair(Of String, Boolean) In visibilitySettings
                    ToggleAnswerVisibility(visiblitySetting.Key, visiblitySetting.Value)
                Next
            End If
            Exit Sub
        End If

        '一時保存、確定時処理時のメッセージ表示
        If Not String.IsNullOrEmpty(Session(S_Answer_ClientMessage)) Then
            Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "myalert", "<script language=JavaScript>alert('" & Session(S_Answer_ClientMessage) & "');</script>", False)
            Session(S_Answer_ClientMessage) = String.Empty
        End If

        _user = DirectCast(Session(S_COM_LoginUser), LoginUser)

        'セッション切れでリダイレクト
        If _user Is Nothing Then
            Response.Redirect(Request.ApplicationPath & Logout_FilePath)
            Exit Sub
        End If

        ViewState("学籍NO") = Session(S_COM_UserCD)
        ViewState("学園CD") = _user.学園CD
        ViewState("PTCD課目別アンケート") = GetPtCd("課目別アンケート")
        ViewState("PTCD課題演習") = GetPtCd("課題演習")
        ViewState("PTCD全体") = GetPtCd("全体")
        Dim ansDate As String = ""
        Dim gakusekiNo As String = ViewState("学籍NO").ToString()
        Dim kenshuKbn As String = ""

        Using q_table As DataTable = Q_Get()
            If q_table Is Nothing OrElse q_table.Rows.Count = 0 Then
                VW質問.Visible = False
                LV質問全体.Visible = False
                uc_TitleBar_課題演習.Visible = False
                VW課題演習.Visible = False
                VW回答.Visible = False
                LV回答全体.Visible = False
                VW講座.Visible = False
                VW自由記入欄.Visible = False
                'CheckListForSeminar.Visible = False
                CheckListForSeminar_12.Visible = False
                CheckListForSeminar_13.Visible = False
                btn_一時保存.Visible = False
                lb_Mes確定.Visible = False
                uc_TitleBar_全体.Visible = False
                btn_確定.Visible = False
                lb_Mes一時保存.Text = "回答できるアンケートがありません。"
                mainBlock.Visible = False
                Exit Sub
            End If
            ViewState("QNO") = q_table.Rows(0)(0).ToString()
            FRM_備考.Text = q_table.Rows(0)(1).ToString.Replace(Environment.NewLine, "<br />")

            '項目見出しの表示
            VW課題演習.Columns(0).HeaderText = q_table.Rows(0)("Q5").ToString()
            VW自由記入欄.Columns(0).HeaderText = q_table.Rows(0)("Q11").ToString()
            VW講義テーマ.Columns(0).HeaderText = q_table.Rows(0)("Q16").ToString()
            VWその他要望.Columns(0).HeaderText = q_table.Rows(0)("Q17").ToString()
            VW業務上問題.Columns(0).HeaderText = q_table.Rows(0)("Q18").ToString()
            VW生活面要望.Columns(0).HeaderText = q_table.Rows(0)("Q19").ToString()
            CheckListForSeminar_12.Columns(0).HeaderText = q_table.Rows(0)("Q12").ToString()
            CheckListForSeminar_13.Columns(0).HeaderText = q_table.Rows(0)("Q13").ToString()

            Dim qno = Convert.ToInt16(ViewState("QNO"))

            '研修区分の取得
            Dim ans_all_table As DataTable = GetAnswerData(qno, gakusekiNo, 1)

            If ans_all_table Is Nothing OrElse ans_all_table.Rows.Count = 0 Then
                Exit Sub
            End If
            ViewState("研修区分") = ans_all_table.Rows(0)("研修区分").ToString()
            ansDate = ans_all_table.Rows(0)("回答日").ToString()
            kenshuKbn = ViewState("研修区分").ToString()

            '要素の表示非表示対応用バインド
            LV質問全体.DataBind()
            LV回答全体.DataBind()

            '研修区分による取得項目の切り替え
            If kenshuKbn = "一般研修" Then
                div_question_detail.Visible = True

                uc_TitleBar_課題演習.Visible = q_table.Rows(0)("Q5一般表示区分").Equals("○")
                VW課題演習.Visible = q_table.Rows(0)("Q5一般表示区分").Equals("○")

                ToggleQuestionVisibility("question6Container", "headerItem6", q_table.Rows(0)("Q6一般表示区分").Equals("○"))
                ToggleQuestionVisibility("question7Container", "headerItem7", q_table.Rows(0)("Q7一般表示区分").Equals("○"))
                ToggleQuestionVisibility("question8Container", "headerItem8", q_table.Rows(0)("Q8一般表示区分").Equals("○"))
                ToggleQuestionVisibility("question9Container", "headerItem9", q_table.Rows(0)("Q9一般表示区分").Equals("○"))
                ToggleQuestionVisibility("question10Container", "headerItem10", q_table.Rows(0)("Q10一般表示区分").Equals("○"))
                ToggleQuestionVisibility("question14Container", "headerItem14", q_table.Rows(0)("Q14一般表示区分").Equals("○"))
                ToggleQuestionVisibility("question15Container", "headerItem15", q_table.Rows(0)("Q15一般表示区分").Equals("○"))
                ToggleQuestionVisibility("question20Container", "headerItem20", q_table.Rows(0)("Q20一般表示区分").Equals("○"))
                ToggleQuestionVisibility("question21Container", "headerItem21", q_table.Rows(0)("Q21一般表示区分").Equals("○"))
                ToggleQuestionVisibility("question22Container", "headerItem22", q_table.Rows(0)("Q22一般表示区分").Equals("○"))
                ToggleAnswerVisibility("answer6Container", q_table.Rows(0)("Q6一般表示区分").Equals("○"))
                ToggleAnswerVisibility("answer7Container", q_table.Rows(0)("Q7一般表示区分").Equals("○"))
                ToggleAnswerVisibility("answer8Container", q_table.Rows(0)("Q8一般表示区分").Equals("○"))
                ToggleAnswerVisibility("answer9Container", q_table.Rows(0)("Q9一般表示区分").Equals("○"))
                ToggleAnswerVisibility("answer10Container", q_table.Rows(0)("Q10一般表示区分").Equals("○"))
                ToggleAnswerVisibility("answer14Container", q_table.Rows(0)("Q14一般表示区分").Equals("○"))
                ToggleAnswerVisibility("answer15Container", q_table.Rows(0)("Q15一般表示区分").Equals("○"))
                ToggleAnswerVisibility("answer20Container", q_table.Rows(0)("Q20一般表示区分").Equals("○"))
                ToggleAnswerVisibility("answer21Container", q_table.Rows(0)("Q21一般表示区分").Equals("○"))
                ToggleAnswerVisibility("answer22Container", q_table.Rows(0)("Q22一般表示区分").Equals("○"))

                ViewState("ItemVisibility") = New Dictionary(Of String, Boolean) From {
                {"answer6Container", q_table.Rows(0)("Q6一般表示区分").Equals("○")},
                {"answer7Container", q_table.Rows(0)("Q7一般表示区分").Equals("○")},
                {"answer8Container", q_table.Rows(0)("Q8一般表示区分").Equals("○")},
                {"answer9Container", q_table.Rows(0)("Q9一般表示区分").Equals("○")},
                {"answer10Container", q_table.Rows(0)("Q10一般表示区分").Equals("○")},
                {"answer14Container", q_table.Rows(0)("Q14一般表示区分").Equals("○")},
                {"answer15Container", q_table.Rows(0)("Q15一般表示区分").Equals("○")},
                {"answer20Container", q_table.Rows(0)("Q20一般表示区分").Equals("○")},
                {"answer21Container", q_table.Rows(0)("Q21一般表示区分").Equals("○")},
                {"answer22Container", q_table.Rows(0)("Q22一般表示区分").Equals("○")}
                }

                VW自由記入欄.Visible = q_table.Rows(0)("Q11一般表示区分").Equals("○")
                VW講義テーマ.Visible = q_table.Rows(0)("Q16一般表示区分").Equals("○")
                VWその他要望.Visible = q_table.Rows(0)("Q17一般表示区分").Equals("○")
                VW業務上問題.Visible = q_table.Rows(0)("Q18一般表示区分").Equals("○")
                VW生活面要望.Visible = q_table.Rows(0)("Q19一般表示区分").Equals("○")

                CheckListForSeminar_12.Columns(0).Visible = q_table.Rows(0)("Q12一般表示区分").Equals("○")
                CheckListForSeminar_13.Columns(0).Visible = q_table.Rows(0)("Q13一般表示区分").Equals("○")

            ElseIf kenshuKbn.Contains("セミナー") Then
                div_question_detail.Visible = False
                VW質問.Columns(3).HeaderText = "" 'ご意見ご感想のナンバリングを外す

                uc_TitleBar_課題演習.Visible = q_table.Rows(0)("Q5セミナー表示区分").Equals("○")
                VW課題演習.Visible = q_table.Rows(0)("Q5セミナー表示区分").Equals("○")
                'LV質問全体の要素の表示非表示
                ToggleQuestionVisibility("question6Container", "headerItem6", q_table.Rows(0)("Q6セミナー表示区分").Equals("○"))
                ToggleQuestionVisibility("question7Container", "headerItem7", q_table.Rows(0)("Q7セミナー表示区分").Equals("○"))
                ToggleQuestionVisibility("question8Container", "headerItem8", q_table.Rows(0)("Q8セミナー表示区分").Equals("○"))
                ToggleQuestionVisibility("question9Container", "headerItem9", q_table.Rows(0)("Q9セミナー表示区分").Equals("○"))
                ToggleQuestionVisibility("question10Container", "headerItem10", q_table.Rows(0)("Q10セミナー表示区分").Equals("○"))
                ToggleQuestionVisibility("question14Container", "headerItem14", q_table.Rows(0)("Q14セミナー表示区分").Equals("○"))
                ToggleQuestionVisibility("question15Container", "headerItem15", q_table.Rows(0)("Q15セミナー表示区分").Equals("○"))
                ToggleQuestionVisibility("question20Container", "headerItem20", q_table.Rows(0)("Q20セミナー表示区分").Equals("○"))
                ToggleQuestionVisibility("question21Container", "headerItem21", q_table.Rows(0)("Q21セミナー表示区分").Equals("○"))
                ToggleQuestionVisibility("question22Container", "headerItem22", q_table.Rows(0)("Q22セミナー表示区分").Equals("○"))

                ToggleAnswerVisibility("answer6Container", q_table.Rows(0)("Q6セミナー表示区分").Equals("○"))
                ToggleAnswerVisibility("answer7Container", q_table.Rows(0)("Q7セミナー表示区分").Equals("○"))
                ToggleAnswerVisibility("answer8Container", q_table.Rows(0)("Q8セミナー表示区分").Equals("○"))
                ToggleAnswerVisibility("answer9Container", q_table.Rows(0)("Q9セミナー表示区分").Equals("○"))
                ToggleAnswerVisibility("answer10Container", q_table.Rows(0)("Q10セミナー表示区分").Equals("○"))
                ToggleAnswerVisibility("answer14Container", q_table.Rows(0)("Q14セミナー表示区分").Equals("○"))
                ToggleAnswerVisibility("answer15Container", q_table.Rows(0)("Q15セミナー表示区分").Equals("○"))
                ToggleAnswerVisibility("answer20Container", q_table.Rows(0)("Q20セミナー表示区分").Equals("○"))
                ToggleAnswerVisibility("answer21Container", q_table.Rows(0)("Q21セミナー表示区分").Equals("○"))
                ToggleAnswerVisibility("answer22Container", q_table.Rows(0)("Q22セミナー表示区分").Equals("○"))

                'LV回答全体の表示非表示情報を保存
                ViewState("ItemVisibility") = New Dictionary(Of String, Boolean) From {
                {"answer6Container", q_table.Rows(0)("Q6セミナー表示区分").Equals("○")},
                {"answer7Container", q_table.Rows(0)("Q7セミナー表示区分").Equals("○")},
                {"answer8Container", q_table.Rows(0)("Q8セミナー表示区分").Equals("○")},
                {"answer9Container", q_table.Rows(0)("Q9セミナー表示区分").Equals("○")},
                {"answer10Container", q_table.Rows(0)("Q10セミナー表示区分").Equals("○")},
                {"answer14Container", q_table.Rows(0)("Q14セミナー表示区分").Equals("○")},
                {"answer15Container", q_table.Rows(0)("Q15セミナー表示区分").Equals("○")},
                {"answer20Container", q_table.Rows(0)("Q20セミナー表示区分").Equals("○")},
                {"answer21Container", q_table.Rows(0)("Q21セミナー表示区分").Equals("○")},
                {"answer22Container", q_table.Rows(0)("Q22セミナー表示区分").Equals("○")}
                }

                VW自由記入欄.Visible = q_table.Rows(0)("Q11セミナー表示区分").Equals("○")
                VW講義テーマ.Visible = q_table.Rows(0)("Q16セミナー表示区分").Equals("○")
                VWその他要望.Visible = q_table.Rows(0)("Q17セミナー表示区分").Equals("○")
                VW業務上問題.Visible = q_table.Rows(0)("Q18セミナー表示区分").Equals("○")
                VW生活面要望.Visible = q_table.Rows(0)("Q19セミナー表示区分").Equals("○")

                CheckListForSeminar_12.Columns(0).Visible = q_table.Rows(0)("Q12セミナー表示区分").Equals("○")
                CheckListForSeminar_13.Columns(0).Visible = q_table.Rows(0)("Q13セミナー表示区分").Equals("○")
            End If

            '課目別の表示非表示の設定反映
            If Not IsDBNull(ans_all_table.Rows(0)("質問5表示")) Then
                VW課題演習.Visible = ans_all_table.Rows(0)("質問5表示").Equals("○")
                uc_TitleBar_課題演習.Visible = ans_all_table.Rows(0)("質問5表示").Equals("○")
            End If

            If Not IsDBNull(ans_all_table.Rows(0)("質問11表示")) Then
                VW自由記入欄.Visible = ans_all_table.Rows(0)("質問11表示").Equals("○")
            End If

            If Not IsDBNull(ans_all_table.Rows(0)("質問12表示")) Then
                CheckListForSeminar_12.Visible = ans_all_table.Rows(0)("質問12表示").Equals("○")
            End If

            If Not IsDBNull(ans_all_table.Rows(0)("質問13表示")) Then
                CheckListForSeminar_13.Visible = ans_all_table.Rows(0)("質問13表示").Equals("○")
            End If

            If Not IsDBNull(ans_all_table.Rows(0)("質問16表示")) Then
                VW講義テーマ.Visible = ans_all_table.Rows(0)("質問16表示").Equals("○")
            End If

            If Not IsDBNull(ans_all_table.Rows(0)("質問17表示")) Then
                VWその他要望.Visible = ans_all_table.Rows(0)("質問17表示").Equals("○")
            End If
            If Not IsDBNull(ans_all_table.Rows(0)("質問18表示")) Then
                VW業務上問題.Visible = ans_all_table.Rows(0)("質問18表示").Equals("○")
            End If

            If Not IsDBNull(ans_all_table.Rows(0)("質問19表示")) Then
                VW生活面要望.Visible = ans_all_table.Rows(0)("質問19表示").Equals("○")
            End If

        End Using

        '回答状況から、ボタンの活性非活性の操作
        If ansDate IsNot "" Then
            btn_一時保存.Enabled = False
            btn_確定.Enabled = False
            lb_timeStamp.Text = ansDate

            '各ビューの無効化
            VW回答.Enabled = False
            LV回答全体.Enabled = False
            VW課題演習.Enabled = False
            VW自由記入欄.Enabled = False
            VW講義テーマ.Enabled = False
            VWその他要望.Enabled = False
            VW業務上問題.Enabled = False
            VW生活面要望.Enabled = False
            CheckListForSeminar_12.Enabled = False
            CheckListForSeminar_13.Enabled = False

        End If

        RenumberHeaders()

    End Sub

#End Region

#Region "***************** コントロールイベント *****************"

    Protected Sub VW回答_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles VW回答.PreRender
        cellVisible()
    End Sub

    Protected Sub VW回答_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles VW回答.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim ptCd = ViewState("PTCD課目別アンケート").ToString()

            '質問1～3
            For itemNo As Integer = 1 To 3
                GetAnswerOptionsForDropDownList(ptCd, itemNo, e)
            Next

            Dim lbl As Label = DirectCast(e.Row.FindControl("lbl_A4"), Label)
            Dim txt As TextBox = DirectCast(e.Row.FindControl("txt_A4"), TextBox)

            ' データ項目を取得
            Dim dataItem As DataRowView = TryCast(e.Row.DataItem, DataRowView)
            If dataItem IsNot Nothing Then
                Dim disp As String = dataItem("質問4表示").ToString()

                '表示・非表示を制御
                If disp = "×" Then
                    txt.Visible = False
                    lbl.Visible = True
                Else
                    txt.Visible = True
                    lbl.Visible = False
                End If
            End If
        End If
    End Sub

    Protected Sub LV質問全体_DataBound(ByVal sender As Object, ByVal e As EventArgs) Handles LV質問全体.DataBound
        ' このタイミングでヘッダーテキストを設定
        'SetHeaderNumbers()
        'RenumberHeaders()
    End Sub

    Protected Sub LV回答全体_ItemDataBound(sender As Object, e As ListViewItemEventArgs) Handles LV回答全体.ItemDataBound
        ' データアイテムかどうかを確認
        If e.Item.ItemType = ListViewItemType.DataItem Then
            Dim ptCd = ViewState("PTCD全体").ToString()

            ' 全体質問1～5 = 質問6～10
            For itemNo As Integer = 6 To 10
                GetAnswerOptionsForLvDropDownList(ptCd, itemNo, e)
            Next

            For itemNo As Integer = 14 To 15
                GetAnswerOptionsForLvDropDownList(ptCd, itemNo, e)
            Next

            '全体質問3つ追加 20250326 S.Iguchi
            For itemNo As Integer = 20 To 22
                GetAnswerOptionsForLvDropDownList(ptCd, itemNo, e)
            Next

            Dim visibilitySettings = TryCast(ViewState("ItemVisibility"), Dictionary(Of String, Boolean))
            If visibilitySettings IsNot Nothing Then
                For Each visiblitySetting As KeyValuePair(Of String, Boolean) In visibilitySettings
                    ToggleAnswerVisibility(visiblitySetting.Key, visiblitySetting.Value)
                Next
            End If

        End If
    End Sub
    Protected Sub CheckListForSeminar_RowDataBound(sender As Object, e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then

            For itemNo As Integer = 12 To 13
                GetAnsCheckList(e, itemNo)
            Next

        End If
    End Sub

    Protected Sub SqlDataSource1_Selecting(sender As Object, e As SqlDataSourceSelectingEventArgs) Handles SqlDataSource1.Selecting
        e.Command.Parameters("@QNO").Value = Convert.ToInt16(ViewState("QNO"))
        e.Command.Parameters("@学籍NO").Value = ViewState("学籍NO").ToString()
        e.Command.Parameters("@回数").Value = "0"
    End Sub

    Protected Sub SqlDataSource1_sub_Selecting(sender As Object, e As SqlDataSourceSelectingEventArgs) Handles SqlDataSource1_sub.Selecting
        e.Command.Parameters("@QNO").Value = Convert.ToInt16(ViewState("QNO"))
        e.Command.Parameters("@学籍NO").Value = ViewState("学籍NO").ToString()
        e.Command.Parameters("@回数").Value = "1"
    End Sub

    Protected Sub SqlDataSource2_Selecting(sender As Object, e As SqlDataSourceSelectingEventArgs) Handles SqlDataSource2.Selecting
        e.Command.Parameters("@学籍NO").Value = ViewState("学籍NO").ToString()
        e.Command.Parameters("@対象日").Value = Now()

    End Sub

    Protected Sub SqlDataSource1_Updating(sender As Object, e As SqlDataSourceCommandEventArgs) Handles SqlDataSource1.Updating

        If ViewState("回答日") IsNot Nothing Then
            e.Command.Parameters("@回答日").Value = CType(ViewState("回答日"), DateTime)
        End If
        '非表示項目はパラメータから外す
        'CommandParamRemove(e)
    End Sub

    Protected Sub SqlDataSource1_sub_Updating(sender As Object, e As SqlDataSourceCommandEventArgs) Handles SqlDataSource1_sub.Updating
        e.Command.Parameters("@回数").Value = 1

        If ViewState("回答日") IsNot Nothing Then
            e.Command.Parameters("@回答日").Value = CType(ViewState("回答日"), DateTime)
        End If
        '非表示項目はパラメータから外す
        'CommandParamRemove(e)
    End Sub

    'ドロップダウンリストの選択した値を更新パラメータに設定
    Protected Sub VW回答_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles VW回答.RowUpdating
        '質問1～3
        For itemNo As Integer = 1 To 3
            UpdateDdlData(itemNo, VW回答, e, SqlDataSource1)
        Next
    End Sub

    Protected Sub CheckListForSeminar_12_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles CheckListForSeminar_12.RowUpdating
        Dim itemNo = 12
        UpdateCheckListData(itemNo, CheckListForSeminar_12, e, SqlDataSource1_sub)
    End Sub

    Protected Sub CheckListForSeminar_13_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles CheckListForSeminar_13.RowUpdating
        Dim itemNo = 13
        UpdateCheckListData(itemNo, CheckListForSeminar_13, e, SqlDataSource1_sub)
    End Sub

    Protected Sub btn_一時保存_Click(sender As Object, e As EventArgs) Handles btn_一時保存.Click
        '一時保存時は、回答日NULLで更新
        ViewState("回答日") = Nothing
        Try
            UpdateAnswerData()

            Dim msg As String = "一時保存しました"
            Session(S_Answer_ClientMessage) = msg
            Response.Redirect(Request.RawUrl.ToString)
        Catch

        End Try
    End Sub

    Protected Sub btn_確定_Click(sender As Object, e As EventArgs) Handles btn_確定.Click

        ViewState("回答日") = DateTime.Now
        Try
            UpdateAnswerData()

            '確定処理完了後、ボタンの非活性化、タイムスタンプ表示
            btn_一時保存.Enabled = False
            btn_確定.Enabled = False
            lb_timeStamp.Text = Now

            Dim msg As String = "アンケートの提出が完了しました"
            Session(S_Answer_ClientMessage) = msg
            Response.Redirect(Request.RawUrl.ToString)
        Catch
            '
        End Try
    End Sub

#End Region

#Region "******************* Sub及びFunction ********************"

    Protected Sub cellVisible()
        Using q_table As DataTable = Q_Get()
            If q_table Is Nothing OrElse q_table.Rows.Count = 0 Then
                Exit Sub
            End If

            For i As Integer = 1 To 4 'DB回答.A1 - .A4
                If IsDBNull(q_table.Rows(0)("Q" & i.ToString)) Then
                    VW回答.Columns.Item(i - 1).Visible = False
                    VW質問.Columns.Item(i - 1).Visible = False
                Else
                    Dim kenshuKbn = ViewState("研修区分").ToString()
                    Dim kenshuDispFlg = q_table.Rows(0)("Q" & i.ToString & "一般表示区分").Equals("○")
                    Dim seminarDispFlg = q_table.Rows(0)("Q" & i.ToString & "セミナー表示区分").Equals("○")

                    If kenshuKbn.Equals("一般研修") Then

                        VW回答.Columns.Item(i - 1).Visible = kenshuDispFlg
                        VW質問.Columns.Item(i - 1).Visible = kenshuDispFlg

                    End If

                    If kenshuKbn.Contains("セミナー") Then
                        VW回答.Columns.Item(i - 1).Visible = seminarDispFlg
                        VW質問.Columns.Item(i - 1).Visible = seminarDispFlg
                    End If

                    If kenshuKbn.Contains("セミナー") AndAlso seminarDispFlg Then

                        If i = 1 Then

                            VW質問.Columns.Item(i - 1).ItemStyle.Width = Unit.Percentage(25)
                            VW回答.Columns.Item(i - 1).ItemStyle.Width = Unit.Percentage(25)
                            Continue For

                        ElseIf i = 4 Then

                            VW質問.Columns.Item(i - 1).ItemStyle.Width = Unit.Percentage(75)
                            VW回答.Columns.Item(i - 1).ItemStyle.Width = Unit.Percentage(75)

                            Continue For
                        End If
                    End If
                End If
            Next

        End Using
    End Sub


    Protected Function Q_Get() As DataTable
        Using spm As New StoredProcedureManager("Q_回答_アンケート_SELECT")
            spm.AddPrmIn("@学籍NO", Data.SqlDbType.VarChar, 20, Session(S_COM_UserCD))
            spm.AddPrmIn("@対象日", Data.SqlDbType.DateTime, Now())
            spm.Fill()

            Return spm.ds.Tables(0)
        End Using
    End Function

    Protected Function GetAnswerData(ByVal qno As Integer, ByVal gakuseki_no As String, ByVal times As String) As DataTable
        Using spm As New StoredProcedureManager("Q_回答_アンケート回答_SELECT")
            spm.AddPrmIn("@QNO", Data.SqlDbType.Int, qno)
            spm.AddPrmIn("@学籍NO", Data.SqlDbType.VarChar, gakuseki_no)
            spm.AddPrmIn("@回数", Data.SqlDbType.Int, times)
            spm.Fill()

            Return spm.ds.Tables(0)
        End Using
    End Function

    Protected Sub UpdateDdlData(itemNo As Integer, GridView As GridView, e As GridViewUpdateEventArgs, src As SqlDataSource)
        Dim ddl As DropDownList = CType(GridView.Rows(e.RowIndex).FindControl(String.Format("ddl_A{0}", itemNo)), DropDownList)

        If ddl IsNot Nothing Then
            Dim sVal As String = ddl.SelectedValue
            src.UpdateParameters(String.Format("A{0}", itemNo)).DefaultValue = sVal
        End If

    End Sub

    Protected Sub UpdateLvDdlData(itemNo As Integer, lv As ListView, e As ListViewUpdateEventArgs, src As SqlDataSource)
        Dim ddl As DropDownList = CType(lv.FindControl(String.Format("ddl_A{0}", itemNo)), DropDownList)

        If ddl IsNot Nothing Then
            Dim sVal As String = ddl.SelectedValue
            src.UpdateParameters(String.Format("A{0}", itemNo)).DefaultValue = sVal
        End If
    End Sub

    Protected Function SetUpdateCheckValues(itemNo As Integer, updateValues As Dictionary(Of String, Object), gv As GridView) As Dictionary(Of String, Object)

        Dim chkList As CheckBoxList = CType(gv.Rows(0).FindControl(String.Format("cbl_{0}", itemNo)), CheckBoxList)

        'その他のテキストボックスと回答CD
        Dim chkAnother As CheckBox = CType(gv.Rows(0).FindControl(String.Format("chk_{0}_another", itemNo)), CheckBox)
        Dim txtAnother As TextBox = CType(gv.Rows(0).FindControl(String.Format("txt_{0}_another", itemNo)), TextBox)
        Dim AnotherChkCd As String = ViewState(String.Format("AnotherCd{0}", itemNo))
        Dim AnotherTxtCd = (Convert.ToInt16(AnotherChkCd) + 1).ToString()

        If chkList IsNot Nothing Then

            Dim sortedItemsWithState = GetSortedItemListWithState(chkList)
            Dim idx As Integer = 1

            '登録ストアドに引数の指定
            For Each itemWithState In sortedItemsWithState
                Dim ansCD As ListItem = itemWithState.Item1
                Dim isChecked As Boolean = itemWithState.Item2

                'A12_1～A12_20,A13_1～A13_20の引数を指定(その他以外)
                updateValues(String.Format("A{0}_{1}", itemNo, idx)) = If(isChecked, "1", "0")
                idx += 1
            Next
        End If

        'その他の内容
        If chkAnother IsNot Nothing Then
            updateValues(String.Format("A{0}_{1}", itemNo, AnotherChkCd)) = If(chkAnother.Checked, "1", "0")
        End If

        If txtAnother IsNot Nothing Then
            If chkAnother.Checked Then
                updateValues(String.Format("A{0}_{1}", itemNo, AnotherTxtCd)) = txtAnother.Text
            Else
                'その他未チェック時は空で更新
                updateValues(String.Format("A{0}_{1}", itemNo, AnotherTxtCd)) = String.Empty
            End If
        End If
        Return updateValues

    End Function

    Protected Sub UpdateCheckListData(itemNo As Integer, GridView As GridView, e As GridViewUpdateEventArgs, src As SqlDataSource)

        Dim chkList As CheckBoxList = CType(GridView.Rows(e.RowIndex).FindControl(String.Format("cbl_{0}", itemNo)), CheckBoxList)

        'その他のテキストボックスと回答CD
        Dim chkAnother As CheckBox = CType(GridView.Rows(e.RowIndex).FindControl(String.Format("chk_{0}_another", itemNo)), CheckBox)
        Dim txtAnother As TextBox = CType(GridView.Rows(e.RowIndex).FindControl(String.Format("txt_{0}_another", itemNo)), TextBox)
        Dim AnotherChkCd As String = ViewState(String.Format("AnotherCd{0}", itemNo))
        Dim AnotherTxtCd = (Convert.ToInt16(AnotherChkCd) + 1).ToString()

        If chkList IsNot Nothing Then

            Dim sortedItemsWithState = GetSortedItemListWithState(chkList)
            Dim idx As Integer = 1

            '登録ストアドに引数の指定
            For Each itemWithState In sortedItemsWithState
                Dim ansCD As ListItem = itemWithState.Item1
                Dim isChecked As Boolean = itemWithState.Item2

                'A12_1～A12_20,A13_1～A13_20の引数を指定(その他以外)
                src.UpdateParameters(String.Format("A{0}_{1}", itemNo, idx)).DefaultValue = If(isChecked, "1", "0")
                idx += 1
            Next
        End If

        'その他の内容
        If chkAnother IsNot Nothing Then
            SqlDataSource1_sub.UpdateParameters(String.Format("A{0}_{1}", itemNo, AnotherChkCd)).DefaultValue = If(chkAnother.Checked, "1", "0")
        End If

        If txtAnother IsNot Nothing Then
            If Not chkAnother.Checked Then
                txtAnother.Text = "" 'その他未チェック時は空で更新
            End If
            SqlDataSource1_sub.UpdateParameters(String.Format("A{0}_{1}", itemNo, AnotherTxtCd)).DefaultValue = txtAnother.Text
        End If
    End Sub
    Protected Sub UpdateAnswerData()

        Dim qNo As Integer = Convert.ToInt16(ViewState("QNO"))
        Dim gakusekiNo As String = ViewState("学籍NO").ToString()
        Dim kenshuKbn As String = ViewState("研修区分").ToString()

        originalDataTable = GetAnswerData(qNo, gakusekiNo, 0)
        originalDataTableAll = GetAnswerData(qNo, gakusekiNo, 1)

        '各ビューの値を更新
        For Each r As GridViewRow In VW回答.Rows
            If IsVwAnsRowModified(r) Then
                VW回答.UpdateRow(r.RowIndex, False)
            End If
        Next
        VW回答.DataBind()

        'VW課題演習、VW回答全体、VW自由記入欄はまとめて更新
        '入力データをDicに格納し、更新ストアドに投げる
        Dim updateValues As New Dictionary(Of String, Object)

        updateValues("A1") = DirectCast(VW回答.Rows(0).FindControl("ddl_A1"), DropDownList).SelectedValue
        updateValues("A2") = DirectCast(VW回答.Rows(0).FindControl("ddl_A2"), DropDownList).SelectedValue
        updateValues("A3") = DirectCast(VW回答.Rows(0).FindControl("ddl_A3"), DropDownList).SelectedValue
        updateValues("A4") = DirectCast(VW回答.Rows(0).FindControl("txt_A4"), TextBox).Text

        For Each row As GridViewRow In VW課題演習.Rows
            If Not row.RowType = DataControlRowType.DataRow Then
                Continue For
            End If
            updateValues("A5") = DirectCast(row.FindControl("txt_A5"), TextBox).Text
        Next

        For Each item As ListViewItem In LV回答全体.Items
            ' ddl_A6からddl_A10までを対象に処理
            For i As Integer = 6 To 10
                Dim ddl As DropDownList = DirectCast(item.FindControl(String.Format("ddl_A{0}", i)), DropDownList)
                If ddl IsNot Nothing Then
                    updateValues(String.Format("A{0}", i)) = ddl.SelectedValue
                End If
            Next

            For i As Integer = 14 To 15
                Dim ddl As DropDownList = DirectCast(item.FindControl(String.Format("ddl_A{0}", i)), DropDownList)
                If ddl IsNot Nothing Then
                    updateValues(String.Format("A{0}", i)) = ddl.SelectedValue
                End If
            Next

            For i As Integer = 20 To 22
                Dim ddl As DropDownList = DirectCast(item.FindControl(String.Format("ddl_A{0}", i)), DropDownList)
                If ddl IsNot Nothing Then
                    updateValues(String.Format("A{0}", i)) = ddl.SelectedValue
                End If
            Next
        Next

        For Each row As GridViewRow In VW自由記入欄.Rows
            If Not row.RowType = DataControlRowType.DataRow Then
                Continue For
            End If
            updateValues("A11") = DirectCast(row.FindControl("txt_A11"), TextBox).Text
        Next

        For Each row As GridViewRow In VW講義テーマ.Rows
            If Not row.RowType = DataControlRowType.DataRow Then
                Continue For
            End If
            updateValues("A16") = DirectCast(row.FindControl("txt_A16"), TextBox).Text
        Next

        For Each row As GridViewRow In VWその他要望.Rows
            If Not row.RowType = DataControlRowType.DataRow Then
                Continue For
            End If
            updateValues("A17") = DirectCast(row.FindControl("txt_A17"), TextBox).Text
        Next

        For Each row As GridViewRow In VW業務上問題.Rows
            If Not row.RowType = DataControlRowType.DataRow Then
                Continue For
            End If
            updateValues("A18") = DirectCast(row.FindControl("txt_A18"), TextBox).Text
        Next

        For Each row As GridViewRow In VW生活面要望.Rows
            If Not row.RowType = DataControlRowType.DataRow Then
                Continue For
            End If
            updateValues("A19") = DirectCast(row.FindControl("txt_A19"), TextBox).Text
        Next

        Dim itemNo = 12
        If CheckListForSeminar_12.Visible Then
            For Each r As GridViewRow In CheckListForSeminar_12.Rows
                If IsVwCheckListRowModified(r, CheckListForSeminar_12, itemNo) Then
                    updateValues = SetUpdateCheckValues(itemNo, updateValues, CheckListForSeminar_12)
                End If
            Next
        End If

        itemNo = 13
        If CheckListForSeminar_13.Visible Then
            For Each r As GridViewRow In CheckListForSeminar_13.Rows
                If IsVwCheckListRowModified(r, CheckListForSeminar_12, itemNo) Then
                    updateValues = SetUpdateCheckValues(itemNo, updateValues, CheckListForSeminar_13)
                End If
            Next
        End If

        '各ビューのデータを一斉更新
        UpdateAnsAll(updateValues)

        '一時保存→何も操作しないで確定処理した場合、回答日のみ更新
        If ViewState("回答日") IsNot Nothing Then
            For Each r As GridViewRow In VW回答.Rows
                '最初の行は全体で更新するからスルー
                If r.RowIndex = 0 Then Continue For
                VW回答.UpdateRow(r.RowIndex, False)
            Next
        End If

    End Sub

    Protected Function IsVwAnsRowModified(r As GridViewRow) As Boolean
        Dim params As Object() = VW回答.DataKeyNames.Select(Function(name As String) VW回答.DataKeys(r.RowIndex).Values(name)).ToArray()
        Dim row As DataRow =
            originalDataTable.Select(String.Format(
            "QNO = '{0}' AND 履修年度 = '{1}' AND 成績年度 = '{2}' AND 分野CD = '{3}' AND 科目CD = '{4}' AND 講座CD = '{5}' AND 回数='{6}' AND 講師CD = '{7}' AND 学籍NO = '{8}' " _
            , params
            ))(0)

        If Not CType(r.FindControl("ddl_A1"), DropDownList).SelectedValue.Equals(row("A1").ToString()) Then Return True
        If Not CType(r.FindControl("ddl_A2"), DropDownList).SelectedValue.Equals(row("A2").ToString()) Then Return True
        If Not CType(r.FindControl("ddl_A3"), DropDownList).SelectedValue.Equals(row("A3").ToString()) Then Return True
        If Not CType(r.FindControl("txt_A4"), TextBox).Text.Equals(row("A4").ToString()) Then Return True

        Return False
    End Function

    Protected Function IsVwAnsAllRowModified(r As GridViewRow) As Boolean

        If Not CType(r.FindControl("ddl_A6"), DropDownList).SelectedValue.Equals(originalDataTableAll.Rows(0)("A6").ToString()) Then Return True
        If Not CType(r.FindControl("ddl_A7"), DropDownList).SelectedValue.Equals(originalDataTableAll.Rows(0)("A7").ToString()) Then Return True
        If Not CType(r.FindControl("ddl_A8"), DropDownList).SelectedValue.Equals(originalDataTableAll.Rows(0)("A8").ToString()) Then Return True
        If Not CType(r.FindControl("ddl_A9"), DropDownList).SelectedValue.Equals(originalDataTableAll.Rows(0)("A9").ToString()) Then Return True
        If Not CType(r.FindControl("ddl_A10"), DropDownList).SelectedValue.Equals(originalDataTableAll.Rows(0)("A10").ToString) Then Return True
        If Not CType(r.FindControl("ddl_A14"), DropDownList).SelectedValue.Equals(originalDataTableAll.Rows(0)("A14").ToString) Then Return True
        If Not CType(r.FindControl("ddl_A15"), DropDownList).SelectedValue.Equals(originalDataTableAll.Rows(0)("A15").ToString) Then Return True
        If Not CType(r.FindControl("ddl_A20"), DropDownList).SelectedValue.Equals(originalDataTableAll.Rows(0)("A20").ToString) Then Return True
        If Not CType(r.FindControl("ddl_A21"), DropDownList).SelectedValue.Equals(originalDataTableAll.Rows(0)("A21").ToString) Then Return True
        If Not CType(r.FindControl("ddl_A22"), DropDownList).SelectedValue.Equals(originalDataTableAll.Rows(0)("A22").ToString) Then Return True

        Return False
    End Function

    Protected Function IsVwWorkRowModified(r As GridViewRow) As Boolean
        If Not CType(r.FindControl("txt_A5"), TextBox).Text.Equals(originalDataTableAll.Rows(0)("A5").ToString()) Then
            SqlDataSource1_sub.UpdateParameters("A5").DefaultValue = CType(r.FindControl("txt_A5"), TextBox).Text
            Return True
        End If

        Return False
    End Function
    Protected Function IsVwFreeSpaceRowModified(r As GridViewRow) As Boolean
        If Not CType(r.FindControl("txt_A11"), TextBox).Text.Equals(originalDataTableAll.Rows(0)("A11").ToString()) Then
            SqlDataSource1_sub.UpdateParameters("A11").DefaultValue = CType(r.FindControl("txt_A11"), TextBox).Text

            Return True
        End If

        Return False
    End Function

    Protected Function IsVwCheckListRowModified(r As GridViewRow, gv As GridView, itemNo As Integer) As Boolean

        Dim params As Object() = gv.DataKeyNames.Select(Function(name As String) gv.DataKeys(r.RowIndex).Values(name)).ToArray()
        Dim row As DataRow =
            originalDataTableAll.Select(String.Format("QNO = '{0}' AND 履修年度 = '{1}' AND 成績年度 = '{2}' AND 分野CD = '{3}' AND 科目CD = '{4}' AND 講座CD = '{5}' AND 回数='{6}' AND 講師CD = '{7}' AND 学籍NO = '{8}' ", params))(0)

        '質問12-13のチェックリスト 入力更新有無チェック
        'For itemNo As Integer = 12 To 13
        Dim chkList As CheckBoxList = CType(r.FindControl(String.Format("cbl_{0}", itemNo)), CheckBoxList)
        Dim chkAnother As CheckBox = CType(r.FindControl(String.Format("chk_{0}_another", itemNo)), CheckBox)
        Dim txtAnother As TextBox = CType(r.FindControl(String.Format("txt_{0}_another", itemNo)), TextBox) 'その他の内容
        Dim sortedItemList As List(Of Tuple(Of ListItem, Boolean)) = GetSortedItemListWithState(chkList)
        Dim AnotherChkCd = ViewState(String.Format("AnotherCd{0}", itemNo)).ToString()
        Dim AnotherTxtCd = (Convert.ToInt16(AnotherChkCd) + 1).ToString()
        Dim idx As Integer = 1

        For Each checkInfo As Tuple(Of ListItem, Boolean) In sortedItemList
            If Not checkInfo.Item2.ToString().Equals(row(String.Format("A{0}_{1}", itemNo, idx)).ToString()) Then Return True
            idx += 1
        Next

        'その他の内容の入力更新有無チェック
        Dim chkStatus As String = If(chkAnother.Checked, "1", "0")
        If Not chkStatus.Equals(row(String.Format("A{0}_{1}", itemNo, AnotherChkCd)).ToString()) Then
            Return True
        End If

        If Not txtAnother.Text.Equals(row(String.Format("A{0}_{1}", itemNo, AnotherTxtCd)).ToString()) Then
            Return True
        End If
        'Next

        Return False
    End Function

    Private Sub GetAnswerOptionsForDropDownList(ptCd As String, itemNo As Integer, e As GridViewRowEventArgs)

        Dim qNo = Convert.ToInt16(ViewState("QNO"))
        Dim gakuenCd = ViewState("学園CD").ToString()
        Dim rowView As DataRowView = DirectCast(e.Row.DataItem, DataRowView)

        Dim lbl As Label = DirectCast(e.Row.FindControl(String.Format("lbl_A{0}", itemNo)), Label)
        Dim ddl As DropDownList = DirectCast(e.Row.FindControl(String.Format("ddl_A{0}", itemNo)), DropDownList)

        Using spm As New StoredProcedureManager("Q_回答_選択肢_SELECT")
            spm.AddPrmIn("@QNO", Data.SqlDbType.Int, qNo)
            spm.AddPrmIn("@PTCD", Data.SqlDbType.VarChar, ptCd)
            spm.AddPrmIn("@質問", Data.SqlDbType.Int, itemNo)
            spm.AddPrmIn("@学園CD", Data.SqlDbType.VarChar, gakuenCd)
            spm.Fill()


            Dim dt As DataTable = spm.ds.Tables(0)

            ' 重複オプションの取得の回避
            For Each row As DataRow In dt.Rows
                Dim item As New ListItem(row("回答").ToString(), row("回答CD").ToString())
                If ddl.Items.FindByValue(item.Value) Is Nothing Then
                    ddl.Items.Add(item)
                End If
            Next

            ddl.DataValueField = "回答CD"
            ddl.DataTextField = "回答"
            ddl.DataBind()

            ' 初期値はデータ値を設定
            Dim selectedValue As String = rowView(String.Format("A{0}", itemNo)).ToString()
            If Not String.IsNullOrEmpty(selectedValue) AndAlso ddl.Items.FindByValue(selectedValue) IsNot Nothing Then
                ddl.SelectedValue = selectedValue
            Else
                ddl.SelectedValue = ""
            End If
        End Using

        ' データ項目を取得
        If rowView IsNot Nothing Then
            Dim disp As String = rowView("質問" & itemNo & "表示").ToString()

            ' 条件に応じて表示・非表示を制御
            If disp = "×" Then
                ddl.Visible = False
                lbl.Visible = True
            Else
                ddl.Visible = True
                lbl.Visible = False
            End If
        End If

    End Sub

    Private Sub GetAnswerOptionsForLvDropDownList(ptCd As String, itemNo As Integer, e As ListViewItemEventArgs)

        Dim qNo = Convert.ToInt16(ViewState("QNO"))
        Dim gakuenCd = ViewState("学園CD").ToString()
        Dim rowView As DataRowView = DirectCast(e.Item.DataItem, DataRowView)

        Dim lbl As Label = DirectCast(e.Item.FindControl(String.Format("lbl_A{0}", itemNo)), Label)
        Dim ddl As DropDownList = DirectCast(e.Item.FindControl(String.Format("ddl_A{0}", itemNo)), DropDownList)

        Using spm As New StoredProcedureManager("Q_回答_選択肢_SELECT")
            spm.AddPrmIn("@QNO", Data.SqlDbType.Int, qNo)
            spm.AddPrmIn("@PTCD", Data.SqlDbType.VarChar, ptCd)
            spm.AddPrmIn("@質問", Data.SqlDbType.Int, itemNo)
            spm.AddPrmIn("@学園CD", Data.SqlDbType.VarChar, gakuenCd)
            spm.Fill()


            Dim dt As DataTable = spm.ds.Tables(0)

            ' 重複オプションの取得の回避
            For Each row As DataRow In dt.Rows
                Dim item As New ListItem(row("回答").ToString(), row("回答CD").ToString())
                If ddl.Items.FindByValue(item.Value) Is Nothing Then
                    ddl.Items.Add(item)
                End If
            Next

            ddl.DataValueField = "回答CD"
            ddl.DataTextField = "回答"
            ddl.DataBind()

            ' 初期値はデータ値を設定
            Dim selectedValue As String = rowView(String.Format("A{0}", itemNo)).ToString()
            If Not String.IsNullOrEmpty(selectedValue) AndAlso ddl.Items.FindByValue(selectedValue) IsNot Nothing Then
                ddl.SelectedValue = selectedValue
            Else
                ddl.SelectedValue = ""
            End If
        End Using

        ' データ項目を取得
        If rowView IsNot Nothing Then
            Dim disp As String = rowView("質問" & itemNo & "表示").ToString()

            ' 条件に応じて表示・非表示を制御
            If disp = "×" Then
                ddl.Visible = False
                lbl.Visible = True
            Else
                ddl.Visible = True
                lbl.Visible = False
            End If
        End If

    End Sub
    'PTCDを取得する
    Private Function GetPtCd(content As String) As String
        Dim ptCd = String.Empty
        Dim pt_table As DataTable = Com_Get_変数TABLE("Q質問PT")

        Dim pt_row = pt_table.AsEnumerable().FirstOrDefault(Function(row) row.Field(Of String)("内容") = content)

        If pt_row IsNot Nothing Then
            ptCd = pt_row.Field(Of String)("CD")
        End If

        Return ptCd
    End Function

    Public Sub UpdateAnsAll(updateValues As Dictionary(Of String, Object))

        For Each entry As KeyValuePair(Of String, Object) In updateValues
            SqlDataSource1_sub.UpdateParameters(entry.Key).DefaultValue = entry.Value
        Next
        SqlDataSource1_sub.UpdateParameters("QNO").DefaultValue = originalDataTableAll.Rows(0)("QNO").ToString
        SqlDataSource1_sub.UpdateParameters("履修年度").DefaultValue = originalDataTableAll.Rows(0)("履修年度").ToString
        SqlDataSource1_sub.UpdateParameters("成績年度").DefaultValue = originalDataTableAll.Rows(0)("成績年度").ToString
        SqlDataSource1_sub.UpdateParameters("分野CD").DefaultValue = originalDataTableAll.Rows(0)("分野CD").ToString
        SqlDataSource1_sub.UpdateParameters("科目CD").DefaultValue = originalDataTableAll.Rows(0)("科目CD").ToString
        SqlDataSource1_sub.UpdateParameters("講座CD").DefaultValue = originalDataTableAll.Rows(0)("講座CD").ToString
        SqlDataSource1_sub.UpdateParameters("回数").DefaultValue = originalDataTableAll.Rows(0)("回数").ToString
        SqlDataSource1_sub.UpdateParameters("講師CD").DefaultValue = originalDataTableAll.Rows(0)("講師CD").ToString
        SqlDataSource1_sub.UpdateParameters("学籍NO").DefaultValue = originalDataTableAll.Rows(0)("学籍NO").ToString

        SqlDataSource1_sub.Update()

    End Sub

    Private Sub GetAnsCheckList(e As GridViewRowEventArgs, itemNo As Integer)

        Dim qNo = Convert.ToInt16(ViewState("QNO"))
        Dim ptCd = ViewState("PTCD全体").ToString()
        Dim gakuenCd = ViewState("学園CD").ToString()
        Dim chkList As CheckBoxList = CType(e.Row.FindControl(String.Format("cbl_{0}", itemNo)), CheckBoxList)
        Dim chkAnother As CheckBox = CType(e.Row.FindControl(String.Format("chk_{0}_another", itemNo)), CheckBox)
        Dim txtAnother As TextBox = CType(e.Row.FindControl(String.Format("txt_{0}_another", itemNo)), TextBox)
        Dim rowView As DataRowView = DirectCast(e.Row.DataItem, DataRowView)

        If chkList IsNot Nothing Then
            Using spm As New StoredProcedureManager("Q_回答_選択肢_SELECT")
                spm.AddPrmIn("@QNO", SqlDbType.Int, qNo)
                spm.AddPrmIn("@PTCD", SqlDbType.VarChar, ptCd)
                spm.AddPrmIn("@質問", SqlDbType.Int, itemNo)
                spm.AddPrmIn("@学園CD", SqlDbType.VarChar, gakuenCd)

                spm.Fill()

                Dim dt As DataTable = spm.ds.Tables(0)

                chkList.Items.Clear()

                'Dictに各選択肢のチェック状態を保持
                Dim idx As Integer = 1
                Dim checkStatusDict As New Dictionary(Of String, Boolean)()
                For Each row As DataRow In dt.Rows
                    Dim optionNo As Integer = Convert.ToInt16(row("回答CD").ToString().Replace("CHK", ""))
                    If optionNo >= 21 Then Continue For '選択肢の最大数は20
                    Dim key As String = String.Format("A{0}_{1}", itemNo, row("回答CD").ToString().Replace("CHK", ""))
                    Dim isChecked As Boolean = rowView(key).ToString() = "1"
                    checkStatusDict.Add(key, isChecked)
                Next

                'チェックボックスリストの作成
                For Each row As DataRow In dt.Rows
                    Dim item As New ListItem()
                    item.Text = row("回答").ToString()
                    item.Value = row("回答CD").ToString()

                    Dim optionNo As Integer = Convert.ToInt16(item.Value.Replace("CHK", ""))
                    If optionNo >= 21 Then Continue For '選択肢の最大数は20

                    ' Dictからチェック状態を取得
                    Dim key As String = String.Format("A{0}_{1}", itemNo, item.Value.Replace("CHK", ""))
                    If checkStatusDict.ContainsKey(key) Then
                        item.Selected = checkStatusDict(key)
                    End If

                    '「その他」の項目のみ別枠で対応のため、IDのみ取得
                    If item.Text = "その他" Then
                        ViewState(String.Format("AnotherCd{0}", itemNo)) = item.Value.Replace("CHK", "") '[その他]の回答CDを格納
                        Continue For
                    End If

                    chkList.Items.Add(item)
                    idx += 1
                Next

                'その他欄の初期値設定
                If ViewState(String.Format("AnotherCd{0}", itemNo)) IsNot Nothing Then
                    Dim AnotherChkCd = ViewState(String.Format("AnotherCd{0}", itemNo)).ToString()
                    Dim AnotherTxtCd = (Convert.ToInt16(AnotherChkCd) + 1).ToString()
                    chkAnother.Checked = rowView(String.Format("A{0}_{1}", itemNo, AnotherChkCd)).ToString() = "1"
                    txtAnother.Text = rowView(String.Format("A{0}_{1}", itemNo, AnotherTxtCd)).ToString()

                    If chkAnother.Checked Then
                        txtAnother.Enabled = True
                    End If
                Else
                    'その他がない場合、固定チェックボックス、テキストボックスを非表示
                    chkAnother.Visible = False
                    txtAnother.Visible = False
                End If

            End Using
        End If

    End Sub

    Private Function GetSortedItemListWithState(chkList As CheckBoxList) As List(Of Tuple(Of ListItem, Boolean))

        Dim sortedItemList As New List(Of Tuple(Of ListItem, Boolean))()

        ' チェック状態も含めたリストの取得
        Dim itemListWithState As New List(Of Tuple(Of ListItem, Boolean))()
        For Each item As ListItem In chkList.Items
            itemListWithState.Add(Tuple.Create(item, item.Selected))
        Next

        ' 回答CD順に並び替え
        sortedItemList = itemListWithState.OrderBy(Of Integer)(Function(i)
                                                                   ' "回答CD"からCHK**の数字部分**のみを抽出
                                                                   Dim match As Match = Regex.Match(i.Item1.Value, "CHK(\d+)")
                                                                   If match.Success Then
                                                                       Return Convert.ToInt16(match.Groups(1).Value)
                                                                   Else
                                                                       Return 0
                                                                   End If
                                                               End Function).ToList()

        Return sortedItemList

    End Function

    Private Sub SetHeaderText(vw As GridView, colNo As Integer, ansNo As String, q_table As DataTable)

        vw.Columns(colNo).HeaderText = IIf(q_table.Rows(0)("sQ" & ansNo).ToString() = "", q_table.Rows(0)("Q" & ansNo).ToString(), q_table.Rows(0)("sQ" & ansNo).ToString())

    End Sub

    ' パラメータに基づき、各項目を表示または非表示にする関数
    Private Sub ToggleQuestionVisibility(questionContainerId As String, headerItemId As String, isVisible As Boolean)

        ' LV質問全体の表示設定を適用
        For Each item As ListViewDataItem In LV質問全体.Items
            Dim questionContainer As Control = item.FindControl(questionContainerId)
            Dim headerItem As Control = LV質問全体.FindControl(headerItemId)

            ' パラメータの値に基づき、コンテナとヘッダの表示を設定
            If questionContainer IsNot Nothing Then
                questionContainer.Visible = isVisible
            End If
            If headerItem IsNot Nothing Then
                headerItem.Visible = isVisible
            End If
        Next
    End Sub

    Private Sub ToggleAnswerVisibility(answerContainerId As String, isVisible As Boolean)

        For Each item As ListViewDataItem In LV回答全体.Items
            Dim answerContainer As Control = item.FindControl(answerContainerId)
            If answerContainer IsNot Nothing Then
                answerContainer.Visible = isVisible
            End If
        Next
    End Sub

    '全体質問のヘッダ質問1～8のナンバリング制御
    Private Sub RenumberHeaders()
        Dim control As Control = LV質問全体
        Dim headerItems As New List(Of HtmlGenericControl)
        FindControlsByClass(control, "header-item", headerItems)

        ' 表示されている順に質問の番号の表示をナンバリング
        Dim visibleCount As Integer = 0
        For Each headerItem As HtmlGenericControl In headerItems
            If headerItem.Visible Then
                visibleCount += 1
                headerItem.InnerText = "質問" & visibleCount
            End If
        Next
    End Sub

    Private Sub FindControlsByClass(ByVal root As Control, ByVal className As String, ByVal result As List(Of HtmlGenericControl))
        If TypeOf root Is HtmlGenericControl Then
            Dim htmlControl As HtmlGenericControl = DirectCast(root, HtmlGenericControl)
            If htmlControl.Attributes("class") IsNot Nothing AndAlso htmlControl.Attributes("class").Contains(className) Then
                result.Add(htmlControl)
            End If
        End If

        For Each child As Control In root.Controls
            FindControlsByClass(child, className, result)
        Next
    End Sub

    Private Sub CommandParamRemove(e As SqlDataSourceCommandEventArgs)
        For itemNo As Integer = 1 To 4
            If Not VW質問.Columns.Item(itemNo - 1).Visible Then
                e.Command.Parameters.RemoveAt(String.Format("@A{0}", itemNo))
            End If
        Next

        If Not VW課題演習.Visible Then
            e.Command.Parameters.RemoveAt("@A5")
        End If

        '全体質問欄　質問NO6-10,14,15, 20-22
        Dim itemNos As Integer() = {6, 7, 8, 9, 10, 14, 15, 20, 21, 22}
        For Each itemNo In itemNos
            Dim containerName As String = String.Format("question{0}Container", itemNo)
            Dim container As Control = LV質問全体.FindControl(containerName)
            If container IsNot Nothing AndAlso Not container.Visible Then
                e.Command.Parameters.RemoveAt(String.Format("@A{0}", itemNo))
            End If
        Next

        If Not VW自由記入欄.Visible Then
            e.Command.Parameters.RemoveAt("@A11")
        End If
        If Not VW講義テーマ.Visible Then
            e.Command.Parameters.RemoveAt("@A16")
        End If
        If Not VWその他要望.Visible Then
            e.Command.Parameters.RemoveAt("@A17")
        End If
        If Not VW業務上問題.Visible Then
            e.Command.Parameters.RemoveAt("@A18")
        End If
        If Not VW生活面要望.Visible Then
            e.Command.Parameters.RemoveAt("@A19")
        End If

    End Sub
#End Region
End Class