在datagrid中,我们可能会需要实现这种功能——列的单选,本身datagrid提供了select命令可以实现这种功能。另为也可以利用HTML 控件中的radiobutton来实现这样的功能,当然这也是我们所习惯的。

      好的,现在来实现它。  首先在页面上加入DataGrid控件。

  • 第一列设置为模板列,在项模板中加入label
  • 再将datagrid绑定上数据

具体格式如下:

〈asp:DataGrid >〈/SelectedItemStyle>

〈ItemStyle ForeColor="#330099" BackColor="White">〈/ItemStyle> 〈HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000">〈/HeaderStyle>

〈FooterStyle ForeColor="#330099" BackColor="#FFFFCC">〈/FooterStyle> 〈Columns>

〈asp:TemplateColumn HeaderText="Select">

〈ItemTemplate>

〈asp:Label >〈/asp:Label>

〈/ItemTemplate>

〈/asp:TemplateColumn>

〈asp:BoundColumn DataField="a" HeaderText="Last Name">〈/asp:BoundColumn> 〈/Columns>

〈PagerStyle HorizontalAlign="Center" ForeColor="#330099" BackColor="#FFFFCC">〈/PagerStyle>

〈/asp:DataGrid>

再在页面上加入一个label(用于显示我们在Datagrid中单选的项)和一个Button(查看选中项),如下:

〈asp:Label >〈/asp:Button〉

    在后台代码中:

  • 在DataGrid的ItemDataBound事件中

         If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
            Dim lbl As Label
            lbl  = e.Item.FindControl("Label2")

            '加入radio
            lbl .Text = "<input type=radio name='myradiogroup' value=" & e.Item.Cells(1).Text & ">"
        End If

  • 在Button的click事件中

        Label3.Text = Request.Form("myradiogroup")

        Dim i As DataGridItem
        For Each i In DataGrid1.Items
            If i.ItemType = ListItemType.AlternatingItem Or i.ItemType = ListItemType.Item Then
                Dim r As Label
                r = i.FindControl("Label2")

                If r.Text.IndexOf(Label3.Text) > 0 Then
                    r.Text = "<input type=radio name='myradiogroup' value=" & i.Cells(1).Text & " checked>"
                Else
                    r.Text = "<input type=radio name='myradiogroup' value=" & i.Cells(1).Text & ">"
                End If
            End If
        Next

         好了,这样就可以实现利用radio实现Datagrid的单选的功能了。

          如图:

          

利用radio实现Datagrid的单选

    

         当我们选中其中一项,点击"查看选中内容"时,如图:

利用radio实现Datagrid的单选

        在vs.net2003、iis5.0测试通过。

相关文章: