使用Radio按钮选择DataGrid行
(读自http://www.dotnetbips.com/displayarticle.aspx?id=147 有源代码下载)
这个问题的出现是因为RadioButtons控件是不能直接加在DataGrid的模板列的。因为DataGrid会给每个单选按钮生成一个唯一名,这样这些单选按钮就不是一个组的了。
解决问题的办法是,在模板列中加入一个Label控件。在DataGrid的ItemDataBound事件中写<INPUT>元素,如:
If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
Dim r As Label
r = e.Item.FindControl("Label2")
r.Text = "<input type=radio name='myradiogroup' value=" & e.Item.Cells(1).Text & ">"
End If
Dim r As Label
r = e.Item.FindControl("Label2")
r.Text = "<input type=radio name='myradiogroup' value=" & e.Item.Cells(1).Text & ">"
End If
如果要获得选中的值,就要用Request.Form来获取了
Label3.Text = Request.Form("myradiogroup")
如果在PostBack之后要保留状态,就要自己做了
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
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