meks
meks

Reputation: 807

Can't determine status of checkbox in Grid View

I have a GridView with Checkbox within it. But I'm having real problem with determining if a check box of a given row is checked or not.

I need to retrieve a certain value from a row and put it into code. But when I iterate through GridView Rows the program doesn't enter the if statement which checks the checkBox'x status.

here is the code of backend:

 Dim Primaryid As String = "Initial stage"
    For Each gvr As GridViewRow In GridView1.Rows

        If (CType(gvr.FindControl("CheckBox1"), CheckBox)).Checked = True Then
            Primaryid = gvr.Cells(1).Text
        End If
    Next gvr

    Dim exmess As String = "alert('" & Primaryid & "')"
    Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", exmess, True)

And here is the code of the GridView. I'm populating it automatically upon the loading of the page:

<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" 
        GridLines="None" Width="1500px">
        <Columns>

                    <asp:TemplateField >
                        <ItemTemplate>
                            <asp:CheckBox ID="CheckBox1" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>

          </Columns>
        <AlternatingRowStyle BackColor="White" />
        <EditRowStyle BackColor="#2461BF" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#EFF3FB" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F5F7FB" />
        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
        <SortedDescendingCellStyle BackColor="#E9EBEF" />
        <SortedDescendingHeaderStyle BackColor="#4870BE" />
    </asp:GridView>

I would be very grateful if you can point me on my mistake.

Upvotes: 0

Views: 2379

Answers (3)

Zo Has
Zo Has

Reputation: 13038

You have to iterate through all the rows & find your checkbox control, then check for its checked state. Check out working example (I converted it into VB using online converter)

Protected Sub btnGetSelectedRows_Click(sender As Object, e As EventArgs)
Dim items = New StringBuilder()
For Each grow As GridViewRow In GridView1.Rows
    Dim chkTemp As CheckBox = DirectCast(grow.FindControl("chkSelectRow"), CheckBox)
    If chkTemp IsNot Nothing Then
        If chkTemp.Checked Then
            items.Append(String.Format("{0},", GridView1.DataKeys(grow.RowIndex)("ProductID").ToString()))
        End If
    End If
Next

If items.Length > 0 Then
        Response.Write("You selected Ids:" & Convert.ToString(items))
    End If

End Sub

And aspx

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" 
        AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="ProductID">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="chkSelectRow" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="ProductID" HeaderText="ProductID" 
                InsertVisible="False" ReadOnly="True" SortExpression="ProductID" />
            <asp:BoundField DataField="ProductName" HeaderText="ProductName" 
                SortExpression="ProductName" />
            <asp:BoundField DataField="SupplierID" HeaderText="SupplierID" 
                SortExpression="SupplierID" />
            <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" 
                SortExpression="CategoryID" />
            <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" 
                SortExpression="QuantityPerUnit" />
            <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" 
                SortExpression="UnitPrice" />
            <asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" 
                SortExpression="UnitsInStock" />
            <asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder" 
                SortExpression="UnitsOnOrder" />
            <asp:BoundField DataField="ReorderLevel" HeaderText="ReorderLevel" 
                SortExpression="ReorderLevel" />
            <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" 
                SortExpression="Discontinued" />
            <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" 
                SortExpression="CategoryName" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" 
        SelectCommand="SELECT * FROM [Alphabetical list of products]"></asp:SqlDataSource>
    <br />

Notice, I have used the

DataKeys

property to access the primary key of the row. I would advise you to do the same as accessing cell values with cellIndex fails in the long run when you change columns on your gridview in future.

Damien.

Upvotes: 1

sp_m
sp_m

Reputation: 2705

Try this may help u.

 Dim Primaryid As String = "Initial stage"
    For Each row As GridViewRow In GridView1.Rows
        Dim chk As CheckBox = TryCast(row.Cells(0).Controls(0), CheckBox)

        If chk.Checked Then
        End If
    Next

Let me know if it's working or not

Upvotes: 0

WozzeC
WozzeC

Reputation: 2660

Try this, it works in winforms. Can't promise that it will work for you. I hard coded the cell value, it should be possible to get the cell the way you do.

Anyhow, main idea is to check the value of the cell rather than trying to get the "checked" value (since they would be the same). So I basically parse the cell value into a boolean object.

For Each r As DataGridViewRow In DataGridView1.Rows
    Dim b As Boolean = False
    Boolean.TryParse(r.Cells("CheckBox1").Value, b)
    If b Then
        'Do stuff
    End If
Next

Edit: wops did it in C# :F Give me a sec and I'll post VB :P

Upvotes: 0

Related Questions