复选框被恢复选中后检查 [英] CheckBox reverts to checked after being unchecked

查看:175
本文介绍了复选框被恢复选中后检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.Net网页包含嵌套GridView控件。在嵌套GridView控件是一个复选框的模板领域。这是的AutoPostBack设置为True,以火的CheckedChanged事件。当你点击复选框将它从检查它恢复到被检查未选中状态发生改变。

我需要知道什么复选框被选中,这样我可以从我的数据表,其中包括当前所选项目中删除。

下载整个项目的.zip 这里

在code这个问题是在浏览文件夹中的文件CreateSchedule.aspx

下面是ASP.Net的GridView的:

 < ASP:GridView控件ID =GridView1=服务器AllowPaging =FALSE的AutoGenerateColumns =FALSEHEIGHT =25像素WIDTH =250像素的cellpadding = 4前景色=#333333网格=无>
        < AlternatingRowStyle背景色=白/>
        < RowStyle HEIGHT =25像素/>
        <柱体和GT;
            < ASP:BoundField的数据字段=课程名的HeaderText =场SORTEX pression =课程名>
            &所述; HeaderStyle宽度=80px高度=25像素/>
            < / ASP:BoundField的>
            < ASP:的TemplateField>
                <&ItemTemplate中GT;
                    < IMG ALT =的风格=光标:指针SRC =图像/ plus.png/>
                    < ASP:面板ID =pnlSections=服务器风格=显示:无>
                        <! - 表内表 - >
                        < ASP:GridView控件ID =GridView2=服务器的AutoGenerateColumns =FALSE的DataKeyNames =CRN前景色=#333333网格=无ShowHeader =FALSE>
                            <柱体和GT;
                                < ASP:的TemplateField>
                                    < ItemStyle宽度=25像素Horizo​​ntalAlign =左/>
                                    <&ItemTemplate中GT;
                                        < ASP:复选框ID =chkCtrl=服务器OnCheckedChanged =CheckedClicked的AutoPostBack =真/>
                                    < / ItemTemplate中>
                                < / ASP:的TemplateField>                                < ASP:BoundField的数据字段=天SORTEX pression =天>
                                    < ItemStyle宽度=60像素/>
                                < / ASP:BoundField的>                                < ASP:BoundField的数据字段=时代SORTEX pression =时代>
                                    < ItemStyle宽度=90像素/>
                                < / ASP:BoundField的>
                            < /专栏>                        < RowStyle VerticalAlign =中背景色=白色/>
                        < SelectedRowStyle背景色=#D1DDF1FONT-粗体=真前景色=#333333/>
                        < SortedAscendingCellStyle背景色=#F5F7FB/>
                        < SortedAscendingHeaderStyle背景色=#6D95E1/>
                        < SortedDescendingCellStyle背景色=#E9EBEF/>
                        < SortedDescendingHeaderStyle背景色=#4870BE/>
                        < / ASP:GridView的>
                        < ASP:SqlDataSource的ID =SqlDataSource2=服务器的ConnectionString =<%$的ConnectionStrings:ConnectionString2%>中的ProviderName =下;%$的ConnectionStrings:ConnectionString2.ProviderName%>中的SelectCommand =SELECT [CRN],[天],[时间]从[ScheduleOfClasses] WHERE([场] =?)>
                            < SelectParameters>
                                < ASP:参数名称=课程类型=字符串/>
                            < / SelectParameters>
                        < / ASP:SqlDataSource的>
                    < / ASP:面板>
                < / ItemTemplate中>
            < / ASP:的TemplateField>
        < /专栏>
        < EditRowStyle背景色=#2461BF/>
        < FooterStyle背景色=#04488AFONT-粗体=真前景色=白/>
        < HeaderStyle背景色=#04488AFONT-粗体=真前景色=白/>
        < PagerStyle背景色=#04488A前景色=白Horizo​​ntalAlign =中心/>
        < RowStyle VerticalAlign =中背景色=白色/>
        < SelectedRowStyle背景色=#D1DDF1FONT-粗体=真前景色=#333333/>
        < SortedAscendingCellStyle背景色=#F5F7FB/>
        < SortedAscendingHeaderStyle背景色=#6D95E1/>
        < SortedDescendingCellStyle背景色=#E9EBEF/>
        < SortedDescendingHeaderStyle背景色=#4870BE/>    < / ASP:GridView的>

下面是此页我的的Page_Load 子。从本质上讲,如果它不是一个回它会创建一个新的DataTable / XML文件并覆盖。如果它是一个回(即当被点击复选框),应该检查那些不再检查任何行,并从数据表中删除。因为它可以让复检我无法测试它的逻辑。

 保护小组的Page_Load(BYVAL发件人为对象,BYVAL E上System.EventArgs)把手Me.Load    如果没有的IsPostBack然后        Me.SetDataSource(ACCT)        创建一个新的DataTable。
        昏暗的表作为数据表=新的DataTable(CourseSelection)        申报的DataColumn和DataRow对象变量。
        昏暗列的DataColumn        创建新的DataColumn,集数据类型的ColumnName
        并将其添加到数据表。
        列=新的DataColumn()
        column.DataType = System.Type.GetType(System.Int32)
        column.ColumnName =CRN
        column.AutoIncrement = FALSE
        column.ReadOnly = TRUE
        column.Unique = TRUE - 同样的CRN不冲突        列添加到DataColumnCollection。
        table.Columns.Add(列)        创建课程列。
        列=新的DataColumn()
        column.DataType = System.Type.GetType(System.String)
        column.ColumnName =当然
        column.AutoIncrement = FALSE
        column.ReadOnly =假
        column.Unique = FALSE        列添加到表中。
        table.Columns.Add(列)        创建指导员列。
        列=新的DataColumn()
        column.DataType = System.Type.GetType(System.String)
        column.ColumnName =指导员
        column.AutoIncrement = FALSE
        column.ReadOnly =假
        column.Unique = FALSE        列添加到表中。
        table.Columns.Add(列)        当然,创建时间列。
        列=新的DataColumn()
        column.DataType = System.Type.GetType(System.String)
        column.ColumnName =coursetime
        column.AutoIncrement = FALSE
        column.ReadOnly =假
        column.Unique = FALSE        列添加到表中。
        table.Columns.Add(列)        创建课程天列。
        列=新的DataColumn()
        column.DataType = System.Type.GetType(System.String)
        column.ColumnName =courseday
        column.AutoIncrement = FALSE
        column.ReadOnly =假
        column.Unique = FALSE        列添加到表中。
        table.Columns.Add(列)        使ID列的主键列,取出,以免唯一键冲突
        昏暗的PrimaryKeyColumns(0)作为的DataColumn
        PrimaryKeyColumns(0)= table.Columns(CRN)
        table.PrimaryKey = PrimaryKeyColumns        昏暗dsXML作为新的数据集(CourseSelections)
        dsXML.Merge(表)
        dsXML.WriteXml(C:\\ TEMP \\ dt.xml,XmlWriteMode.WriteSchema)
        Else语句要在工作
    其他
        昏暗nestedCounter为整数= 0
        昏暗rowCounter为整数= 0
        昏暗的主题作为字符串
        昏暗的DS作为新的数据集
        XML文件目录
        ds.ReadXml(C:\\ TEMP \\ dt.xml)        昏暗的表作为新的DataTable
        表= ds.Tables(CourseSelection)        昏暗CheckedCRNs作为新的ArrayList
        主体=左(GridView1.Rows(1).Cells(0)的ToString(),4)
        对于每一行作为GridViewRow在GridView1.Rows
            昏暗NestedGridView作为GridView控件= GridView1.Rows(rowCounter).FindControl(GridView2)
            nestedCounter = 0
            对于每一个R作为GridViewRow在NestedGridView.Rows
                如果r.RowType = DataControlRowType.DataRow然后
                    昏暗chkRow作为复选框= TryCast(r.Cells(0).FindControl(chkCtrl),复选框)
                    如果chkRow.Checked然后
                        CheckedCRNs.Add(NestedGridView.DataKeys(nestedCounter).Value.ToString())
                    万一
                万一
                nestedCounter = nestedCounter + 1
            下一个
            rowCounter = rowCounter + 1
        下一个
        昏暗的foundRows()作为的DataRow
        如果不表格。选取(当然喜欢与&个体放大器;*)。长度= CheckedCRNs.Count然后
            foundRows =表格。选取(当然喜欢与&个体放大器;*)
            对于i = 0到foundRows.GetUpperBound(0)
                如果未CheckedCRNs.Contains(foundRows(ⅰ)(0))。然后
                    table.Rows(ⅰ).Delete()
                万一
            接下来,我
            昏暗dsXML作为新的数据集(CourseSelections)
            dsXML.Merge(表)
            dsXML.WriteXml(C:\\ TEMP \\ dt.xml,XmlWriteMode.WriteSchema)
        万一
    万一
结束小组

CheckedClicked子:

 保护小组CheckedClicked(发送者为对象,E作为EventArgs的)    '变量是从数据库中提取,
    昏暗课程作为字符串=
    昏暗CourseTime作为字符串=
    昏暗CourseDay作为字符串=
    昏暗的导师作为字符串=
    用于行和列的位置变量
    昏暗的CRN作为整数
    昏暗nestedCounter为整数= 0
    昏暗rowCounter为整数= 0
    昏暗的DS作为新的数据集
    颜色变量
    昏暗colorOfClass作为字符串=
    colorOfClass = getColorOfClasses(colorPosition)
    XML文件目录
    ds.ReadXml(C:\\ TEMP \\ dt.xml)    昏暗的表作为新的DataTable
    表= ds.Tables(CourseSelection)    对于每一行作为GridViewRow在GridView1.Rows
        昏暗NestedGridView作为GridView控件= GridView1.Rows(rowCounter).FindControl(GridView2)
        nestedCounter = 0
        对于每一个R作为GridViewRow在NestedGridView.Rows
            如果r.RowType = DataControlRowType.DataRow然后
                昏暗chkRow作为复选框= TryCast(r.Cells(0).FindControl(chkCtrl),复选框)
                如果chkRow.Checked然后
                    如果表格。选取(CRN ='与& NestedGridView.DataKeys(nestedCounter).Value.ToString()及')。长度= 0。然后
                        CRN = NestedGridView.DataKeys(nestedCounter).Value.ToString()
                    万一
                万一
            万一
            nestedCounter = nestedCounter + 1
        下一个
        rowCounter = rowCounter + 1
    下一个    昏暗CON作为新的OleDbConnection
    尝试
        使用CON
            con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings(ConnectionString2)。的ConnectionString
            con.Open()
            使用CMD =新的OleDbCommand
                cmd.Connection = CON
                cmd.CommandText =选择课程,时间,天,导师FROM ScheduleOfClasses WHERE CRN =&放大器; CRN
                使用ORDR作为OleDbDataReader = cmd.ExecuteReader
                    获取列的每个值
                    虽然(oRDR.Read)
                        当然= oRDR.GetValue(0)
                        CourseTime = oRDR.GetValue(1)
                        CourseDay = oRDR.GetValue(2)
                        讲师= oRDR.GetValue(3)
                    虽然结束
                使用完
                con.Close()
            使用完
        使用完
    抓住EX为例外
        抛出新的异常(ex.Message)
    最后
        con.Close()
    结束Try    昏暗卓尔作为的DataRow    卓尔= table.NewRow()
    卓尔(CRN)= CINT(CRN)
    卓尔(套餐)=课程
    卓尔(指导员)=导师
    卓尔(coursetime)= CourseTime
    卓尔(CourseDay)= CourseDay
    table.Rows.Add(卓尔)
    arrayOfCRNs.Add(CRN)    昏暗NewDs作为新的数据集(CourseSelections)    NewDs.Merge(表)
    NewDs.WriteXml(C:\\ TEMP \\ dt.xml,XmlWriteMode.WriteSchema)    通过上课日循环时暗淡cDay作为字符串='当前日期
    昏暗CCOL由于是基于cDay整数= 0'当前列那一套
    昏暗STARTROW作为整数'表中的行该类启动
    暗淡ClassLength作为表中的行的整数= 0'Number来在基于所述长度类着色
    昏暗StartHours作为字符串= MID(CourseTime,3,2)当天的小时的上课
    选择案例StartHours
        情况下为00'当类在小时开始,STARTROW被计算为所述相关小时
            STARTROW =(CINT(左(CourseTime,2)) - 8)* 4
        案30'当类开始于一小时的底部,STARTROW被计算为所述相关_
            小时加2到帐户三十分钟
            STARTROW =(CINT(左(CourseTime,2)) - 8)* 4 + 2
    结束选择    一类类长度是总分钟每小时15分钟之分,四舍五入
    ClassLength = Math.Floor((CINT(MID(CourseTime,6,4)) - CINT(左(CourseTime,4)))/ 15)
    转化率从类长度= 7,5个细胞
    ClassLength = ClassLength - ((CINT(中间(CourseTime,6,2)) - CINT(左(CourseTime,2)))* 2)    当然日内字符串的大小数目,每天周一至周五检查字符串    对于n为整数= 1要CourseDay.Length
        cDay = MID(CourseDay,N,1)'设置cDay到第n天
        选择案例cDay
            案M
                CCOL = 0
            案T
                CCOL = 1
            案W
                CCOL = 2
            字母r
                CCOL = 3
            字母f
                CCOL = 4
        结束选择        昏暗fillRowCounter作为整数= 1        填充表具有正确的数据
        对于乌鸦作为整数= STARTROW要STARTROW + ClassLength - 1            如果当前行是被4整除然后添加一个;这是由于第一列的行跨度
            如果乌鸦mod4 = 0,则CCOL = CCOL + 1
            schedule.Rows(乌鸦).Cells(CCOL).BgColor = colorOfClass
            如果fillRowCounter = 1,则schedule.Rows(乌鸦).Cells(CCOL).InnerText = CINT(CRN)
            如果fillRowCounter = 2那么schedule.Rows(乌鸦).Cells(CCOL).InnerText =课程
            如果fillRowCounter = 3然后schedule.Rows(乌鸦).Cells(CCOL).InnerText =讲师
            如果fillRowCounter> 3然后schedule.Rows(乌鸦).Cells(CCOL).InnerText =
            如果乌鸦mod4 = 0,则CCOL = CCOL - 1
            fillRowCounter = fillRowCounter + 1        接下来乌鸦
    下n

更新

我改变了我的GridView的数据绑定在的Page_Load 而不是一个SqlDataSource。但是我仍然有和以前相同的问题。下面是我的分,我打电话给最初绑定GridView的。

 保护小组的setDataSource(除作为字符串)
    昏暗的connectionString作为字符串= ConfigurationManager.ConnectionStrings(ConnectionString2)。的ConnectionString
    昏暗的queryString作为字符串=SELECT [课程名] FROM [课程] WHERE([SubjectID] ='&放大器;主题&安培;')
    昏暗DataKeyArray作为字符串()= {课程名}
    昏暗的DS作为新的数据集()    尝试
        连接到数据库并运行查询。
        昏暗的连接作为新的OleDbConnection(的connectionString)
        昏暗的适配器作为新OleDbDataAdapter的(的queryString,连接)        填充DataSet。
        adapter.Fill(DS)
    抓住EX为例外
        连接失败。显示错误消息。
        'Message.Text =无法连接到数据库。
    结束Try    运行查询并结合所产生的DataSet
    到GridView控件。
    如果(ds.Tables.Count大于0)然后
        GridView1.DataSource = DS
        GridView1.DataKeyNames = DataKeyArray
        GridView1.DataBind()
        ds.Dispose()
        ds.Clear()
    其他
        'Message.Text =无法连接到数据库。
    万一    昏暗rowCounter为整数= 0
    昏暗DataKeyArray2作为字符串()= {CRN}
    对于每一行作为GridViewRow在GridView1.Rows
        昏暗NestedGridView作为GridView控件= GridView1.Rows(rowCounter).FindControl(GridView2)
        昏暗gView = GridView1
        的queryString =SELECT [CRN],[天],[时间]从[ScheduleOfClasses] WHERE([场] ='&放大器; GridView1.DataKeys(rowCounter).value的&安培;')
        尝试
            连接到数据库并运行查询。
            昏暗的连接作为新的OleDbConnection(的connectionString)
            昏暗的适配器作为新OleDbDataAdapter的(的queryString,连接)            填充DataSet。
            adapter.Fill(DS)
        抓住EX为例外
            连接失败。显示错误消息。
            'Message.Text =无法连接到数据库。
        结束Try        运行查询并结合所产生的DataSet
        到GridView控件。
        如果(ds.Tables.Count大于0)然后
            NestedGridView.DataSource = DS
            NestedGridView.DataKeyNames = DataKeyArray2
            NestedGridView.DataBind()
            ds.Dispose()
            ds.Clear()
        其他
            'Message.Text =无法连接到数据库。
        万一
        rowCounter = rowCounter + 1
    下一个结束小组

更新2

当取消选中一个框后调试的Page_Load 事件时,网页上的复选框看似选中,但 chkRow.Checked 有一个值为true,即使出现复选框在网页上选中。 (chkRow是正在被选中的复选框)

更新3

我有所突破的。我想通了,与复选框的问题是,嵌套的GridView位于坍塌和使用JavaScript扩展面板内。本质上,它是在ASP.Net中的错误时,控制为禁止对的Page_Load 键,然后再启用。我想通了这一点,因为我的 GridView2 chkCtrl 不能在VB中被引用,因此 GridView2 未初始化的的Page_Load 。我也想通了通过阅读<一href=\"http://stackoverflow.com/questions/1523606/asp-net-checkbox-value-at-postback-is-wrong?lq=1\">this.该解决方案中提到创建一个隐藏字段,将其设置为其他复选框的价值,但我不确定如何做到这一点与我的情况。

当我注释掉面板的复选框取消选中预期和ClickedChanged被激发。不过,我需要的可折叠的面板,因为它是一个大量数据的一切扩展。我在想,如果我可以开始加载所有GridView的,然后塌陷它们的Page_Load ,但我不知道该怎么做,要么。

下面是最最新的aspx我的GridView,这个时候包括code为我的面板:

 &LT;脚本类型=文/ JavaScript的SRC =htt​​p://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js &GT;&LT; / SCRIPT&GT;&LT;%'使用加号和减号图像显示降下来的类%&GT;
&LT;脚本类型=文/ JavaScript的&GT;
    $([来源* =加])。生活(点击,函数(){
        $(本).closest(TR)后(&LT; TR&GT;&LT; TD&GT;&LT; / TD&GT;&LT; TD colspan值='999'&gt;中。+ $(本)。接下来()HTML ()+&下; / TD&GT;&下; / TR&gt;中)
        $(本).attr(SRC,图像/ minus.png);
    });
    $([来源* =减])。生活(点击,函数(){
        $(本).attr(SRC,图像/ plus.png);
        $(本).closest(TR)的next()remove()方法。;
    });
&LT; / SCRIPT&GT;&LT;%'网格视图表'%&GT;    &LT; ASP:GridView控件ID =GridView1=服务器AllowPaging =FALSE的AutoGenerateColumns =FALSEHEIGHT =25像素WIDTH =250像素的cellpadding =4前景色=#333333网格=无&GT;
        &LT; AlternatingRowStyle背景色=白/&GT;
        &LT; RowStyle HEIGHT =25像素/&GT;
        &LT;柱体和GT;
            &LT; ASP:BoundField的数据字段=课程名的HeaderText =场SORTEX pression =课程名&GT;
            &所述; HeaderStyle宽度=80px高度=25像素/&GT;
            &LT; / ASP:BoundField的&GT;
            &LT; ASP:的TemplateField&GT;
                &LT;&ItemTemplate中GT;
                    &LT; IMG ALT =的风格=光标:指针SRC =图像/ plus.png/&GT;
                    &LT; ASP:面板ID =pnlSections=服务器风格=显示:无&GT;
                        &LT;! - 表内表 - &GT;
                        &LT; ASP:GridView控件ID =GridView2=服务器的AutoGenerateColumns =FALSE的DataKeyNames =CRN前景色=#333333网格=无ShowHeader =FALSE&GT;
                            &LT;柱体和GT;
                                &LT; ASP:的TemplateField&GT;
                                    &LT; ItemStyle宽度=25像素Horizo​​ntalAlign =左/&GT;
                                    &LT;&ItemTemplate中GT;
                                        &LT; ASP:复选框ID =chkCtrl=服务器OnCheckedChanged =CheckedClicked的AutoPostBack =真/&GT;
                                    &LT; / ItemTemplate中&GT;
                                &LT; / ASP:的TemplateField&GT;                                &LT; ASP:BoundField的数据字段=天SORTEX pression =天&GT;
                                    &LT; ItemStyle宽度=60像素/&GT;
                                &LT; / ASP:BoundField的&GT;                                &LT; ASP:BoundField的数据字段=时代SORTEX pression =时代&GT;
                                    &LT; ItemStyle宽度=90像素/&GT;
                                &LT; / ASP:BoundField的&GT;
                            &LT; /专栏&GT;                        &LT; RowStyle VerticalAlign =中背景色=白色/&GT;
                        &LT; SelectedRowStyle背景色=#D1DDF1FONT-粗体=真前景色=#333333/&GT;
                        &LT; SortedAscendingCellStyle背景色=#F5F7FB/&GT;
                        &LT; SortedAscendingHeaderStyle背景色=#6D95E1/&GT;
                        &LT; SortedDescendingCellStyle背景色=#E9EBEF/&GT;
                        &LT; SortedDescendingHeaderStyle背景色=#4870BE/&GT;
                        &LT; / ASP:GridView的&GT;
                        &LT; ASP:SqlDataSource的ID =SqlDataSource2=服务器的ConnectionString =&LT;%$的ConnectionStrings:ConnectionString2%&gt;中的ProviderName =下;%$的ConnectionStrings:ConnectionString2.ProviderName%&gt;中的SelectCommand =SELECT [CRN],[天],[时间]从[ScheduleOfClasses] WHERE([场] =?)&GT;
                            &LT; SelectParameters&GT;
                                &LT; ASP:参数名称=课程类型=字符串/&GT;
                            &LT; / SelectParameters&GT;
                        &LT; / ASP:SqlDataSource的&GT;
                    &LT; / ASP:面板&gt;
                &LT; / ItemTemplate中&GT;
            &LT; / ASP:的TemplateField&GT;
        &LT; /专栏&GT;
        &LT; EditRowStyle背景色=#2461BF/&GT;
        &LT; FooterStyle背景色=#04488AFONT-粗体=真前景色=白/&GT;
        &LT; HeaderStyle背景色=#04488AFONT-粗体=真前景色=白/&GT;
        &LT; PagerStyle背景色=#04488A前景色=白Horizo​​ntalAlign =中心/&GT;
        &LT; RowStyle VerticalAlign =中背景色=白色/&GT;
        &LT; SelectedRowStyle背景色=#D1DDF1FONT-粗体=真前景色=#333333/&GT;
        &LT; SortedAscendingCellStyle背景色=#F5F7FB/&GT;
        &LT; SortedAscendingHeaderStyle背景色=#6D95E1/&GT;
        &LT; SortedDescendingCellStyle背景色=#E9EBEF/&GT;
        &LT; SortedDescendingHeaderStyle背景色=#4870BE/&GT;    &LT; / ASP:GridView的&GT;


解决方案

的问题是,包含复选框的GridView2是在的Page_Load 禁用。它最初是被禁用,因为在GridView嵌套一个可折叠的面板内。我删除了面板,一切完美的作品。

我可能会发布一个不同的问题,询问得到可折叠的面板工作。

I have a ASP.Net web page that includes a nested GridView. Within the nested GridView is a template field with a CheckBox. This AutoPostBack is set to True in order to fire the CheckedChanged event. When you click a CheckBox to change it from the checked to unchecked state it reverts back to being checked.

I need to know what CheckBox is unchecked so that I can remove it from my DataTable that includes currently selected items.

Download entire project .zip here

The code for this problem is in the CreateSchedule.aspx file in the Views folder.

Here is the ASP.Net for the GridView:

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

Here is my Page_Load sub for this page. Essentially if it is not a post back it creates a new DataTable/Xml file and overwrites. If it is a post back (ie. when CheckBox is clicked) it should be checking for any rows that are no longer checked and removing it from the DataTable. I cannot test the logic of it because it gets rechecked.

    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

CheckedClicked 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

UPDATE

I changed my GridViews to data bind on Page_Load rather than having a SqlDataSource. However I am still having the same issue as before. Below is my sub that I call to initially bind the GridView.

    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

UPDATE 2

When debugging the Page_Load event after unchecking a box, the checkbox on the web page appears to be unchecked but chkRow.Checked has a value of true even though the checkbox appears unchecked on the web page. (chkRow is the checkbox that was being unchecked)

UPDATE 3

I have made somewhat of a breakthrough. I figured out that the problem with the checkboxes is that the nested gridview is located within a panel that collapses and expands using JavaScript. Essentially it is a bug in ASP.Net when a control is disable on Page_Load and then enabled later. I figured this out because my GridView2 and chkCtrl are not able to be referenced in VB and therefore the GridView2 is not initialized on Page_Load. I also figured it out by reading this. The solution mentions creating a hidden field and setting it to the value of the other checkbox but I am unsure of how to do that with my situation.

When I comment out the panel, the checkboxes uncheck as expected and ClickedChanged is fired. However, I need the collapsible panel because it is a lot of data with everything expanded. I was thinking that if I could initially load all of GridViews and then collapse them on Page_Load but I don't know how to do that either.

Here is the most up to date aspx for my GridView, this time including the code for my panel:

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

解决方案

The problem is that the GridView2 that contains the checkboxes is disabled on Page_Load. It is initially disabled because the gridview is nested inside a collapsible panel. I removed the panel and everything works perfectly.

I may post a different question to inquire about getting the collapsible panel to work.

这篇关于复选框被恢复选中后检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆