今天看了一篇类似的文章,实现DataGrid内的CheckBox的客户端实现,于是想用服务器端代码实现,于是就开始尝试!
aspx 代码如下
<asp:datagrid id="dgdScoreshow" style="Z-INDEX: 101; LEFT: 120px; POSITION: absolute; TOP: 40px"
runat="server" Height="179px" Width="536px">
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" Runat="server" AutoPostBack="True" OnCheckedChanged="checkchange"></asp:CheckBox>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkchoose" Runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>
请注意这部分代码:
<asp:CheckBox ID="chkAll" Runat="server" AutoPostBack="True" OnCheckedChanged="checkchange"></asp:CheckBox>
在里添加一个CheckBox,这样就可以实现在Header部分显示一个复选框,还要注意AutoPostBack=True,否则无非实现。
后台代码里写一个public函数,注意要有相关的参数。
提取演示数据部分,注意Not IsPostBack
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'在此处放置初始化页的用户代码
If Not IsPostBack Then
Dim cnn As New SqlConnection("data source=localhost;initial catalog=model;integrated security=sspi")
Dim cmd As New SqlCommand("select * from sysusers", cnn)
Dim adapter As New SqlDataAdapter(cmd)
Dim dst As New DataSet
Try
adapter.Fill(dst)
dgdScoreshow.DataSource = dst.Tables(0).DefaultView
dgdScoreshow.DataBind()
Catch ex As Exception
Response.Write(ex.Message)
End Try
End If
End Sub
自定义函数部分
Public Sub checkchange(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim item As DataGridItem
For Each item In dgdScoreshow.Items
Dim chk As CheckBox
chk = item.FindControl("chkchoose")
If CType(sender, CheckBox).Checked Then
chk.Checked = True
Else
chk.Checked = False
End If
Next
End Sub
到次为止就可以实现服务器端代码控制 DataGrid中CheckBox的全选了。