Z.V
Z.V

Reputation: 1471

CheckBox in GridView get value

I have the following code

HTML:

            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
                <Columns>
                    <asp:TemplateField HeaderText="Checkbox">
                        <ItemTemplate>
                            <asp:CheckBox ID="chkb" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="ID" Visible="false">
                        <ItemTemplate>
                            <asp:Label ID="lblId" runat="server" Text='<%# Eval("Id")%>'>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Name">
                        <ItemTemplate>
                            <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name")%>'>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Country">
                        <ItemTemplate>
                            <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country")%>'>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>

                </Columns>
            </asp:GridView>

Code behind:

Protected Sub btnExcel_Click(sender As Object, e As EventArgs) Handles btnExcel.Click
        Debug.WriteLine("Clicked")
        For Each row As GridViewRow In GridView1.Rows
            Dim chk As CheckBox = row.FindControl("chkb")
            If chk.Checked Then
                Dim lbl As Label = row.FindControl("lblId")
                Debug.WriteLine(chk.Checked)
                Debug.WriteLine(lbl.Text)
            End If
        Next
    End Sub

Is there something wrong around the checkbox section? because I can get the ouput "Clicked" but can't seem to get the output for

Debug.WriteLine(chk.Checked)
Debug.WriteLine(lbl.Text)

Also, I cannot get the value whether the chk.Checked when I debug.

Upvotes: 0

Views: 6172

Answers (1)

Thirisangu Ramanathan
Thirisangu Ramanathan

Reputation: 614

Try this:

 If Not Page.IsPostBack Then
 GridView1.DataSourceID = dataTable
 GridView1.DataBind()
 End If

Upvotes: 1

Related Questions