在datagrid 的模板列中加入CheckBox ,如果对datagrid设置分页,前一页已经选中的CheckBox在回到原页时,CheckBox的状态会变为初始状态。
如果想保存CheckBox的状态,则可以用Session保存,我是这样实现的:
1、首先,建立datagrid.
<asp:datagrid id="datagrid1" style="Z-INDEX: 101; LEFT: 12px; POSITION: absolute; TOP: 88px" runat="server" AllowPaging="True" Width="416px" Height="248px">
<AlternatingItemStyle BackColor="#EEEEEE"></AlternatingItemStyle>
<ItemStyle Font-Size="12px" Font-Names="宋体"></ItemStyle>
<HeaderStyle Font-Size="12px" Font-Names="宋体" BackColor="#00CCFF"></HeaderStyle>
<FooterStyle HorizontalAlign="Center"></FooterStyle>
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox id="CheckBox1" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</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翻页后的状态保存问题.
<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> <script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>