Datagrid & checkbox

L

Lee Trotter

I have a datagrid with a checkbox colum created using a template colum

How can I reference the checkboxes at run time though code?

Thanks

Lee
 
K

Ken Cox [Microsoft MVP]

Hi Lee,

You need to loop through the datagrid items (rows) and then find the
checkbox control. Then test if it is checked.

For Each dgItem In Me.DataGrid1.Items
chkSelected = dgItem.FindControl("chkSelect")
If chkSelected.Checked Then
Label2.Text = Label2.Text & _
chkSelected.UniqueID & "<br>"
End If
Next


Full source below.

Does this help?

Ken
Microsoft MVP [ASP.NET]
Toronto


Private Sub Page_Load _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
If Not IsPostBack Then
DataGrid1.DataSource = CreateDataSource()
DataGrid1.DataBind()
End If
End Sub

Private Sub btnModifier_Click _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnModifier.Click
Dim dgItem As DataGridItem
Dim chkSelected As CheckBox
Label2.Text = ""
For Each dgItem In Me.DataGrid1.Items
chkSelected = dgItem.FindControl("chkSelect")
If chkSelected.Checked Then
Label2.Text = Label2.Text & _
chkSelected.UniqueID & "<br>"
End If
Next
End Sub

Function CreateDataSource() As DataTable
Dim dt As New DataTable
Dim dr As DataRow
dt.Columns.Add(New DataColumn _
("IntegerValue", GetType(Int32)))
dt.Columns.Add(New DataColumn _
("StringValue", GetType(String)))
dt.Columns.Add(New DataColumn _
("CurrencyValue", GetType(Double)))
dt.Columns.Add _
(New DataColumn("Boolean", GetType(Boolean)))
Dim i As Integer
For i = 0 To 8
dr = dt.NewRow()
dr(0) = i
dr(1) = "Item " + i.ToString()
dr(2) = 1.23 * (i + 1)
dr(3) = (i = 4)
dt.Rows.Add(dr)
Next i
Return dt
End Function 'CreateDataSource


<asp:DataGrid id="DataGrid1" runat="server">
<Columns>
<asp:TemplateColumn HeaderText="Boolean Value">
<ItemTemplate>
<asp:CheckBox id=chkSelect runat="server" Checked='<%#
DataBinder.Eval(Container, "DataItem.Boolean") %>' >
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Boolean Value">
<ItemTemplate>
<asp:Label id="Label1" runat="server">
<%# IIF(DataBinder.Eval(Container, "DataItem.Boolean"),"Yes","No")
%>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<P>
<asp:Label id="Label2" runat="server"></asp:Label></P>
<P>
<asp:Button id="btnModifier" runat="server"
Text="Button"></asp:Button></P>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top