当前位置: 首页 > 知识库问答 >
问题:

复选框在取消选中后恢复为选中

皇甫鸿远
2023-03-14

下载整个项目。zip在这里

此问题的代码在Views文件夹中的CreateSchedule.aspx文件中。

以下是GridView的ASP.NET:

    <asp:GridView ID="GridView1" runat="server" AllowPaging="False" AutoGenerateColumns="False" Height="25px" Width="250px" CellPadding="4" ForeColor="#333333" GridLines="None">
        <AlternatingRowStyle BackColor="White" />
        <RowStyle Height="25px" />
        <Columns>
            <asp:BoundField DataField="CourseName"  HeaderText="Course" SortExpression="CourseName" >
            <HeaderStyle Width="80px" height="25px"/>
            </asp:BoundField>
            <asp:TemplateField>
                <ItemTemplate>
                    <img alt = "" style="cursor: pointer" src="images/plus.png" />
                    <asp:Panel ID="pnlSections" runat="server" Style="display: none"> 
                        <!-- Table inside the table -->
                        <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="CRN" ForeColor="#333333" GridLines="None" ShowHeader="False">
                            <Columns>
                                <asp:TemplateField>
                                    <ItemStyle Width="25px" HorizontalAlign="left"/>
                                    <ItemTemplate>
                                        <asp:CheckBox ID="chkCtrl" runat="server" OnCheckedChanged="CheckedClicked" AutoPostBack="True"  />
                                    </ItemTemplate>
                                </asp:TemplateField>

                                <asp:BoundField DataField="Days" SortExpression="Days" >
                                    <ItemStyle Width="60px" />
                                </asp:BoundField>

                                <asp:BoundField DataField="Time" SortExpression="Time" >
                                    <ItemStyle Width="90px" />
                                </asp:BoundField>
                            </Columns>

                        <RowStyle VerticalAlign="Middle" BackColor="white" />
                        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#F5F7FB" />
                        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                        <SortedDescendingCellStyle BackColor="#E9EBEF" />
                        <SortedDescendingHeaderStyle BackColor="#4870BE" />
                        </asp:GridView>
                        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>" ProviderName="<%$ ConnectionStrings:ConnectionString2.ProviderName %>" SelectCommand="SELECT [CRN], [Days], [Time] FROM [ScheduleOfClasses] WHERE ([Course] = ?)">
                            <SelectParameters>
                                <asp:Parameter Name=" Course" Type="String" />
                            </SelectParameters>
                        </asp:SqlDataSource>
                    </asp:Panel>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EditRowStyle BackColor="#2461BF" />
        <FooterStyle BackColor="#04488A" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#04488A" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#04488A" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle VerticalAlign="Middle" BackColor="white" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F5F7FB" />
        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
        <SortedDescendingCellStyle BackColor="#E9EBEF" />
        <SortedDescendingHeaderStyle BackColor="#4870BE" />

    </asp:GridView>
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not IsPostBack Then

        Me.SetDataSource("ACCT")

        ' Create a new DataTable. 
        Dim table As DataTable = New DataTable("CourseSelection")

        ' Declare variables for DataColumn and DataRow objects. 
        Dim column As DataColumn

        ' Create new DataColumn, set DataType, ColumnName  
        ' and add to DataTable.    
        column = New DataColumn()
        column.DataType = System.Type.GetType("System.Int32")
        column.ColumnName = "crn"
        column.AutoIncrement = False
        column.ReadOnly = True
        column.Unique = True '- same CRN does not conflict

        ' Add the Column to the DataColumnCollection.
        table.Columns.Add(column)

        ' Create course column.
        column = New DataColumn()
        column.DataType = System.Type.GetType("System.String")
        column.ColumnName = "course"
        column.AutoIncrement = False
        column.ReadOnly = False
        column.Unique = False

        ' Add the column to the table.
        table.Columns.Add(column)

        ' Create instructor column.
        column = New DataColumn()
        column.DataType = System.Type.GetType("System.String")
        column.ColumnName = "instructor"
        column.AutoIncrement = False
        column.ReadOnly = False
        column.Unique = False

        ' Add the column to the table.
        table.Columns.Add(column)

        ' Create course time column.
        column = New DataColumn()
        column.DataType = System.Type.GetType("System.String")
        column.ColumnName = "coursetime"
        column.AutoIncrement = False
        column.ReadOnly = False
        column.Unique = False

        ' Add the column to the table.
        table.Columns.Add(column)

        ' Create course day column.
        column = New DataColumn()
        column.DataType = System.Type.GetType("System.String")
        column.ColumnName = "courseday"
        column.AutoIncrement = False
        column.ReadOnly = False
        column.Unique = False

        ' Add the column to the table.
        table.Columns.Add(column)

        ' Make the ID column the primary key column, taken out to avoid conflict of unique key
        Dim PrimaryKeyColumns(0) As DataColumn
        PrimaryKeyColumns(0) = table.Columns("crn")
        table.PrimaryKey = PrimaryKeyColumns

        Dim dsXML As New DataSet("CourseSelections")
        dsXML.Merge(table)
        dsXML.WriteXml("c:\temp\dt.xml", XmlWriteMode.WriteSchema)
        ' Else statement to be worked on
    Else
        Dim nestedCounter As Integer = 0
        Dim rowCounter As Integer = 0
        Dim subject As String
        Dim ds As New DataSet
        ' XML File Directory
        ds.ReadXml("c:\temp\dt.xml")

        Dim table As New DataTable
        table = ds.Tables("CourseSelection")

        Dim CheckedCRNs As New ArrayList
        subject = Left(GridView1.Rows(1).Cells(0).ToString(), 4)
        For Each row As GridViewRow In GridView1.Rows
            Dim NestedGridView As GridView = GridView1.Rows(rowCounter).FindControl("GridView2")
            nestedCounter = 0
            For Each r As GridViewRow In NestedGridView.Rows
                If r.RowType = DataControlRowType.DataRow Then
                    Dim chkRow As CheckBox = TryCast(r.Cells(0).FindControl("chkCtrl"), CheckBox)
                    If chkRow.Checked Then
                        CheckedCRNs.Add(NestedGridView.DataKeys(nestedCounter).Value.ToString())
                    End If
                End If
                nestedCounter = nestedCounter + 1
            Next
            rowCounter = rowCounter + 1
        Next
        Dim foundRows() As DataRow
        If Not table.Select("course like '" & subject & "*'").Length = CheckedCRNs.Count Then
            foundRows = table.Select("course like '" & subject & "*'")
            For i = 0 To foundRows.GetUpperBound(0)
                If Not CheckedCRNs.Contains(foundRows(i)(0)) Then
                    table.Rows(i).Delete()
                End If
            Next i
            Dim dsXML As New DataSet("CourseSelections")
            dsXML.Merge(table)
            dsXML.WriteXml("c:\temp\dt.xml", XmlWriteMode.WriteSchema)
        End If
    End If
End Sub
    Protected Sub CheckedClicked(sender As Object, e As EventArgs)

    ' Variables to be pulled from Database
    Dim Course As String = ""
    Dim CourseTime As String = ""
    Dim CourseDay As String = ""
    Dim Instructor As String = ""
    ' Variables used for position of columns and rows
    Dim crn As Integer
    Dim nestedCounter As Integer = 0
    Dim rowCounter As Integer = 0
    Dim ds As New DataSet
    ' Color variables
    Dim colorOfClass As String = ""
    colorOfClass = getColorOfClasses(colorPosition)


    ' XML File Directory
    ds.ReadXml("c:\temp\dt.xml")

    Dim table As New DataTable
    table = ds.Tables("CourseSelection")

    For Each row As GridViewRow In GridView1.Rows
        Dim NestedGridView As GridView = GridView1.Rows(rowCounter).FindControl("GridView2")
        nestedCounter = 0
        For Each r As GridViewRow In NestedGridView.Rows
            If r.RowType = DataControlRowType.DataRow Then
                Dim chkRow As CheckBox = TryCast(r.Cells(0).FindControl("chkCtrl"), CheckBox)
                If chkRow.Checked Then
                    If table.Select("CRN='" & NestedGridView.DataKeys(nestedCounter).Value.ToString() & "'").Length = 0 Then
                        crn = NestedGridView.DataKeys(nestedCounter).Value.ToString()
                    End If
                End If
            End If
            nestedCounter = nestedCounter + 1
        Next
        rowCounter = rowCounter + 1
    Next

    Dim con As New OleDbConnection
    Try
        Using con
            con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString2").ConnectionString
            con.Open()
            Using cmd = New OleDbCommand
                cmd.Connection = con
                cmd.CommandText = "SELECT Course, Time, Days, Instructor FROM ScheduleOfClasses WHERE CRN= " & crn
                Using oRDR As OleDbDataReader = cmd.ExecuteReader
                    'Gets columns for each value
                    While (oRDR.Read)
                        Course = oRDR.GetValue(0)
                        CourseTime = oRDR.GetValue(1)
                        CourseDay = oRDR.GetValue(2)
                        Instructor = oRDR.GetValue(3)
                    End While
                End Using
                con.Close()
            End Using
        End Using
    Catch ex As Exception
        Throw New Exception(ex.Message)
    Finally
        con.Close()
    End Try

    Dim dRow As DataRow

    dRow = table.NewRow()
    dRow("crn") = CInt(crn)
    dRow("course") = Course
    dRow("instructor") = Instructor
    dRow("coursetime") = CourseTime
    dRow("CourseDay") = CourseDay
    table.Rows.Add(dRow)
    arrayOfCRNs.Add(crn)

    Dim NewDs As New DataSet("CourseSelections")

    NewDs.Merge(table)
    NewDs.WriteXml("c:\temp\dt.xml", XmlWriteMode.WriteSchema)

    Dim cDay As String = ""   'Current day when looping through class days
    Dim cCol As Integer = 0   'Current column that is set based on the cDay
    Dim StartRow As Integer   'Row in the table that the class starts
    Dim ClassLength As Integer = 0   'Number of rows in the table to be colored in based on the length of the class
    Dim StartHours As String = Mid(CourseTime, 3, 2)   'The hour of the day that the class starts 




    Select Case StartHours
        Case "00"   'When the class starts on the hour, StartRow is calculated to the correlated hour
            StartRow = (CInt(Left(CourseTime, 2)) - 8) * 4
        Case "30"   'When the class starts at the bottom of the hour, StartRow is calculated to the correlated _
            'hour plus 2 to account for thirty minutes
            StartRow = (CInt(Left(CourseTime, 2)) - 8) * 4 + 2
    End Select

    'Class length of a class is the total minutes divided by 15 minutes per hour, rounded down
    ClassLength = Math.Floor((CInt(Mid(CourseTime, 6, 4)) - CInt(Left(CourseTime, 4))) / 15)
    'Conversion from Class Length = 7, to 5 cells
    ClassLength = ClassLength - ((CInt(Mid(CourseTime, 6, 2)) - CInt(Left(CourseTime, 2))) * 2)

    'Number of course days as size of String, checking String for each day Monday-Friday 

    For n As Integer = 1 To CourseDay.Length
        cDay = Mid(CourseDay, n, 1)   'Set cDay to the nth day
        Select Case cDay
            Case "M"
                cCol = 0
            Case "T"
                cCol = 1
            Case "W"
                cCol = 2
            Case "R"
                cCol = 3
            Case "F"
                cCol = 4
        End Select

        Dim fillRowCounter As Integer = 1

        ' Populate the table with the correct data
        For cRow As Integer = StartRow To StartRow + ClassLength - 1

            'If the current row is divisible by 4 then add one; this is due to the row span of the first column
            If cRow Mod 4 = 0 Then cCol = cCol + 1
            schedule.Rows(cRow).Cells(cCol).BgColor = colorOfClass
            If fillRowCounter = 1 Then schedule.Rows(cRow).Cells(cCol).InnerText = CInt(crn)
            If fillRowCounter = 2 Then schedule.Rows(cRow).Cells(cCol).InnerText = Course
            If fillRowCounter = 3 Then schedule.Rows(cRow).Cells(cCol).InnerText = Instructor
            If fillRowCounter > 3 Then schedule.Rows(cRow).Cells(cCol).InnerText = ""
            If cRow Mod 4 = 0 Then cCol = cCol - 1
            fillRowCounter = fillRowCounter + 1

        Next cRow
    Next n
    Protected Sub SetDataSource(Subject As String)
    Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString2").ConnectionString
    Dim queryString As String = "SELECT [CourseName] FROM [Courses] WHERE ([SubjectID] = '" & Subject & "')"
    Dim DataKeyArray As String() = {"CourseName"}
    Dim ds As New DataSet()

    Try
        ' Connect to the database and run the query.
        Dim connection As New OleDbConnection(connectionString)
        Dim adapter As New OleDbDataAdapter(queryString, connection)

        ' Fill the DataSet.
        adapter.Fill(ds)
    Catch ex As Exception
        ' The connection failed. Display an error message.
        'Message.Text = "Unable to connect to the database."
    End Try

    ' Run the query and bind the resulting DataSet
    ' to the GridView control.
    If (ds.Tables.Count > 0) Then
        GridView1.DataSource = ds
        GridView1.DataKeyNames = DataKeyArray
        GridView1.DataBind()
        ds.Dispose()
        ds.Clear()
    Else
        'Message.Text = "Unable to connect to the database."
    End If



    Dim rowCounter As Integer = 0
    Dim DataKeyArray2 As String() = {"CRN"}
    For Each row As GridViewRow In GridView1.Rows
        Dim NestedGridView As GridView = GridView1.Rows(rowCounter).FindControl("GridView2")
        Dim gView = GridView1
        queryString = "SELECT [CRN], [Days], [Time] FROM [ScheduleOfClasses] WHERE ([Course] = '" & GridView1.DataKeys(rowCounter).Value & "')"
        Try
            ' Connect to the database and run the query.
            Dim connection As New OleDbConnection(connectionString)
            Dim adapter As New OleDbDataAdapter(queryString, connection)

            ' Fill the DataSet.
            adapter.Fill(ds)
        Catch ex As Exception
            ' The connection failed. Display an error message.
            'Message.Text = "Unable to connect to the database."
        End Try

        ' Run the query and bind the resulting DataSet
        ' to the GridView control.
        If (ds.Tables.Count > 0) Then
            NestedGridView.DataSource = ds
            NestedGridView.DataKeyNames = DataKeyArray2
            NestedGridView.DataBind()
            ds.Dispose()
            ds.Clear()
        Else
            'Message.Text = "Unable to connect to the database."
        End If
        rowCounter = rowCounter + 1
    Next

End Sub

在取消选中某个框后调试page_load事件时,网页上的复选框显示为未选中,但chkrow.check的值为true,即使该复选框在网页上显示为未选中。(chkRow是未选中的复选框)

更新3

我取得了一些突破。我发现复选框的问题在于嵌套的gridview位于使用JavaScript折叠和展开的面板中。本质上,当控件在page_load上禁用,然后在以后启用时,这是ASP.NET中的一个bug。我发现了这一点,因为我的gridview2chkctrl不能在VB中引用,因此page_load上没有初始化gridview2。我看了这个也想通了。解决方案提到创建一个隐藏字段并将其设置为其他复选框的值,但我不确定如何在我的情况下做到这一点。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<%'Using plus and minus images to show drop down of classes'%>
<script type="text/javascript">
    $("[src*=plus]").live("click", function () {
        $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
        $(this).attr("src", "images/minus.png");
    });
    $("[src*=minus]").live("click", function () {
        $(this).attr("src", "images/plus.png");
        $(this).closest("tr").next().remove();
    });
</script>

<%'Grid View Table'%>

    <asp:GridView ID="GridView1" runat="server" AllowPaging="False" AutoGenerateColumns="False" Height="25px" Width="250px" CellPadding="4" ForeColor="#333333" GridLines="None">
        <AlternatingRowStyle BackColor="White" />
        <RowStyle Height="25px" />
        <Columns>
            <asp:BoundField DataField="CourseName"  HeaderText="Course" SortExpression="CourseName" >
            <HeaderStyle Width="80px" height="25px"/>
            </asp:BoundField>
            <asp:TemplateField>
                <ItemTemplate>
                    <img alt = "" style="cursor: pointer" src="images/plus.png" />
                    <asp:Panel ID="pnlSections" runat="server" Style="display: none">  
                        <!-- Table inside the table -->
                        <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="CRN" ForeColor="#333333" GridLines="None" ShowHeader="False">
                            <Columns>
                                <asp:TemplateField>
                                    <ItemStyle Width="25px" HorizontalAlign="left"/>
                                    <ItemTemplate>
                                        <asp:CheckBox ID="chkCtrl" runat="server" OnCheckedChanged="CheckedClicked" AutoPostBack="True"  />
                                    </ItemTemplate>
                                </asp:TemplateField>

                                <asp:BoundField DataField="Days" SortExpression="Days" >
                                    <ItemStyle Width="60px" />
                                </asp:BoundField>

                                <asp:BoundField DataField="Time" SortExpression="Time" >
                                    <ItemStyle Width="90px" />
                                </asp:BoundField>
                            </Columns>

                        <RowStyle VerticalAlign="Middle" BackColor="white" />
                        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#F5F7FB" />
                        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                        <SortedDescendingCellStyle BackColor="#E9EBEF" />
                        <SortedDescendingHeaderStyle BackColor="#4870BE" />
                        </asp:GridView>
                        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>" ProviderName="<%$ ConnectionStrings:ConnectionString2.ProviderName %>" SelectCommand="SELECT [CRN], [Days], [Time] FROM [ScheduleOfClasses] WHERE ([Course] = ?)">
                            <SelectParameters>
                                <asp:Parameter Name=" Course" Type="String" />
                            </SelectParameters>
                        </asp:SqlDataSource>
                    </asp:Panel> 
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EditRowStyle BackColor="#2461BF" />
        <FooterStyle BackColor="#04488A" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#04488A" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#04488A" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle VerticalAlign="Middle" BackColor="white" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F5F7FB" />
        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
        <SortedDescendingCellStyle BackColor="#E9EBEF" />
        <SortedDescendingHeaderStyle BackColor="#4870BE" />

    </asp:GridView>

共有1个答案

舒嘉德
2023-03-14

这听起来很像是您忘了在绑定gridview数据的page_load事件中检查页面是否回发。因此,每次未选中复选框时,您都会无意中重新绑定gridview,这就是为什么复选框会恢复到原始状态(选中)。

If Not IsPostBack Then
      //bind gridview
Else
      //other stuff
End

更新

我认为这是gridviews与SqlDataSource一起使用时的回发问题。您可能希望检查以下资源,甚至可能希望更改数据绑定方法:

https://stackoverflow.com/a/18165161/1845408

 类似资料:
  • 我创建了一个windows窗体(到目前为止)只包含复选框。构造函数接受一个参数:。对于这个数组中的每个字符串,我都会创建一个复选框。 例如: null 那么,当另一个复选框调用uncheck时,是否有一种方法可以告诉我的复选框不要运行? 下面是我的代码(它都是手工编写的,所以没有使用visual studio设计器):

  • 我正在尝试一个Woocommerce票证插件。默认情况下,该插件会显示一个表,其中包含多个票证变体作为产品,并在下面显示一个文本字段作为其数量和一个提交按钮,以将产品添加到购物车中。 我想用单选按钮或复选框替换这个文本字段,这样用户就可以选择一种类型的票证,然后点击提交按钮将其中的一部分添加到购物车中。 我的想法是在foreach循环中创建一个复选框或单选按钮,该复选框或单选按钮的值为quanti

  • 在我取消选中RadioButton或单击组中的另一个RadioButton后,我的RadioButton组中的RadioButton会留下一个黑色的复选框。如何防止这种情况发生? 发生在我的API 19真实设备上,而不是我的API 27 编辑:_________________________________________________ 尝试使用无法使用的自定义选择器 主题: Bump还是找不

  • 我试图创建一个表单,该表单顶部有一个复选框,当用户选中该复选框时,它会选择其他特定的复选框,但不是所有复选框。我很难通过反复试验或搜索找到答案。我唯一能找到的就是“全选”选项。不是我想要的。 理想情况下,当用户选中“管理包”旁边的复选框时,我想要“Chrome外观组”和“远程启动” 下面是代码和我在这方面的基本尝试,但它不起作用。提前谢谢。 超文本标记语言: Javascript 我不知道这个Ja

  • 问题内容: 如何使用JavaScript,jQuery或Vanilla选中/取消选中复选框? 问题答案: Javascript: jQuery(1.6+): jQuery(1.5-):

  • 我有一个复选框,其中有一对项目,当我单击该复选框时,该项目将添加到名为currentDevice的状态,但当我取消选中该项目时,它将保留“添加项目”,而不是删除它。 当我取消选中该框时,如何从状态中删除项。Im使用“反应本机元素”复选框。谢谢你 代码: