Read checkbox state in ASP.Net datagrid

This datagrid on my aspx page...

<asp:DataGrid id="dgLineItems" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateColumn HeaderText="Select">
<ItemTemplate>
<asp:CheckBox id="cbSelect" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="LNITMSEQ" HeaderText="Line ID"></asp:BoundColumn>
<asp:BoundColumn DataField="ITEMNMBR" HeaderText="Item ID"></asp:BoundColumn>
<asp:BoundColumn DataField="ITEMDESC" HeaderText="Item Description"></asp:BoundColumn>
<asp:BoundColumn DataField="UOFM" HeaderText="UOM"></asp:BoundColumn>
<asp:BoundColumn DataField="QUANTITY" HeaderText="Qty" DataFormatString="{0:N0}">
<ItemStyle HorizontalAlign="Right"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="UNITPRCE" HeaderText="Price" DataFormatString="{0:N2}">
<ItemStyle HorizontalAlign="Right"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="XTNDPRCE" HeaderText="Ext Price" DataFormatString="{0:N2}">
<ItemStyle HorizontalAlign="Right"></ItemStyle>
</asp:BoundColumn>
</Columns>
</asp:DataGrid></P>

This code for a button on the aspx page...

  Private Sub buttonNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonNext.Click
        Dim dgItem As DataGridItem
        Dim i As Integer = 0
        For Each dgItem In dgLineItems.Items
            Dim myCheckbox As CheckBox = CType(dgItem.Cells(0).Controls(1), CheckBox)
            If myCheckbox.Checked = True Then
                i += 1
            End If
        Next
        doSomething(i)
    End Sub

... "i" is always zero even if I check some of the checkboxes.  Any suggestions?  Thanks.
jschnei555Asked:
Who is Participating?
 
laotzi2000Commented:
Did you rebind a data set to the datagrid control in Page_Load everytime?
If that's true, you should bind it only when it is not a postback.

For example:
If Not IsPostBack Then
  dg.DataSource = ds
  dg.DataBind
End If
0
 
jschnei555Author Commented:
Thanks a lot!
0
 
appariCommented:
try like this, try using FindControl method.


 Private Sub buttonNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonNext.Click

        Dim dgItem As DataGridItem
        Dim i As Integer = 0

        For Each dgItem In dgLineItems.Items

            Dim myCheckbox As CheckBox = CType(dgItem.FindControl("cbSelect"), CheckBox)
            If myCheckbox.Checked = True Then
                i += 1
            End If
        Next
        doSomething(i)
End Sub
0
 
jschnei555Author Commented:
appari, I already gave the points to laozti2000 for answering the question, but I do appreciate your comment.  That's a nice trick.  
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.