利用Session纪录datagrid模板列中CheckBox的状态

在 DataGrid 的模板列中加入CheckBox ,如果对DataGrid设置分页,前一页已经选中的CheckBox在回到原页时,CheckBox的状态会变为初始状态。

如果想保存checkbox的状态,则可以用Session保存,我是这样实现的:

1、首先,建立DataGrid.

 1<asp:datagrid allowpaging="True" height="248px" id="DataGrid1" runat="server" style="Z-INDEX: 101; LEFT: 12px; POSITION: absolute; TOP: 88px" width="416px">
 2<alternatingitemstyle backcolor="#EEEEEE"></alternatingitemstyle>
 3<itemstyle font-names="宋体" font-size="12px"></itemstyle>
 4<headerstyle backcolor="#00CCFF" font-names="宋体" font-size="12px"></headerstyle>
 5<footerstyle horizontalalign="Center"></footerstyle>
 6<columns>
 7<asp:templatecolumn>
 8<itemtemplate>
 9<asp:checkbox id="CheckBox1" runat="server"></asp:checkbox>
10</itemtemplate>
11</asp:templatecolumn>
12</columns>
13</asp:datagrid>

2、在Global.asax文件中, Session_Start事件中 建立 Session

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' 在会话启动时激发
Dim checks As Boolean() = New Boolean(10000) {}
Dim i As Integer
For i = 0 To 10000
checks(i) = False
Next
Session.Add("CheckBoxchecks", checks)
End Sub

3.在DataGrid的 PageIndexChanged事件中:

Private Sub DataGrid1_PageIndexChanged( ByVal source As Object , ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles DataGrid1.PageIndexChanged

Dim count As Integer

Dim cnn As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\UserLog.mdb")

Dim da As New OleDb.OleDbDataAdapter("select * from mm", cnn)

da.Fill(dst)

count = dst.Tables(0).Rows.Count 'DataGrid中的记录总数;

Dim check As Boolean ()

check = Me .Session("checkboxchecks") 'check()是记录checkbox状态的数组,用session保存。

Dim j As Integer

For j = 0 To DataGrid1.PageSize - 1

Dim Che As CheckBox = DataGrid1.Items(j).Cells(0).FindControl("CheckBox1")

If Not Che Is Nothing Then

If Che.Checked = True Then

check(DataGrid1.CurrentPageIndex * DataGrid1.PageSize + j) = True

Else

check(DataGrid1.CurrentPageIndex * DataGrid1.PageSize + j) = False

End If

End If

Next

DataGrid1.CurrentPageIndex = e.NewPageIndex

Dim ds As New DataSet()

da.Fill(ds, "a")

DataGrid1.DataSource = ds

DataGrid1.DataBind()

Dim i As Integer

For i = 0 To DataGrid1.PageSize - 1

Dim Cx2 As CheckBox = DataGrid1.Items(i).Cells(0).FindControl("CheckBox1")

If check(DataGrid1.CurrentPageIndex * DataGrid1.PageSize + i) = True Then

Cx2.Checked = True

Else

Cx2.Checked = False

End If

Next

End Sub

** 这样就可以利用Session实现checkbox翻页后的状态保存问题. **

Published At
Categories with Web编程
Tagged with
comments powered by Disqus