Solved

Checkbox in gridview value not recognized on submit

Posted on 2013-05-15
7
565 Views
Last Modified: 2013-05-16
I have a databound gridview that I have added a checkbox column to.  When an end user clicks a submit button I loop through the rows on the gridview and if the checkbox is checked I save some of the gridview values to a SQL backend.  It fires correctly and loops through the rows fine but it doesn't seem to see a checked box.  I am a novice in asp.net so this may be simple but I am not seeing it.  

Here is my code:
 For Each row As GridViewRow In Gridview1.Rows

If DirectCast(row.FindControl("mycheckboxcontrol"), System.Web.UI.WebControls.CheckBox).Checked = True Then


                'Perform save here


            End If





        Next

Open in new window


Just to be through here is the top of the .vb file:

Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Imports System.Data

Partial Class _Default
    Inherits System.Web.UI.Page
    Protected WithEvents chkUseContact As Global.System.Web.UI.WebControls.CheckBox

Open in new window

0
Comment
Question by:pensiongenius
7 Comments
 

Author Comment

by:pensiongenius
ID: 39169683
Upon further investigation it is most likely something related to the postback but I am still stumped.
0
 
LVL 15

Accepted Solution

by:
rajeeshmca earned 500 total points
ID: 39170700
Hi,

Could you please paste your code where u call the function to load the grid..

Are you loading the grid on every postback in the page_load.. If so , use the IsPostback property to determine when this needs to be loaded..

If Not IsPostback Then
    LoadGrid()
End If

Otherwise pls post the code so that i can review on it..

Regards
Rajeesh
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 39170873
You need to FindControl in the cell not row

Change

If DirectCast(row.FindControl("mycheckboxcontrol"), System.Web.UI.WebControls.CheckBox).Checked = True Then


to

If DirectCast(row.Cells(ColumnIndex).FindControl("mycheckboxcontrol"), System.Web.UI.WebControls.CheckBox).Checked = True Then
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 15

Expert Comment

by:rajeeshmca
ID: 39170955
Hi CodeCruiser,

I dont think we need to specify Cells. We can find directly from Row. ie.. Row.FindControl()

Regards
Rajeesh
0
 
LVL 16

Expert Comment

by:Rose Babu
ID: 39171552
Hi, if you created the checkboxfield then convert that into templatefield as like below then loop the grid

<asp:GridView ID="GridView4" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="CheckBox1" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField AccessibleHeaderText="Column1" DataField="Column1" HeaderText="Column 1" />
        <asp:BoundField AccessibleHeaderText="Column2" DataField="Column2" HeaderText="Column 2" />
        <asp:BoundField AccessibleHeaderText="Column3" DataField="Column3" HeaderText="Column 3" />
        <asp:BoundField AccessibleHeaderText="Column4" DataField="Column4" HeaderText="Column 4" />
        <asp:BoundField AccessibleHeaderText="Column5" DataField="Column5" HeaderText="Column 5" />
    </Columns>
</asp:GridView>

Open in new window

and instead of for each, try to use for loop as like below

Dim selectedRows As String = ""

For i = 0 To GridView4.Rows.Count - 1

    Dim chkBox As New CheckBox
    chkBox = DirectCast(GridView4.Rows(i).FindControl("CheckBox1"), CheckBox)

    If chkBox.Checked Then
        ' Checked
        selectedRows = selectedRows & i & ","

    End If

Next

selectedRows = selectedRows.TrimEnd(",")

Open in new window

0
 

Author Comment

by:pensiongenius
ID: 39171830
Here is where I create the grid on the page.  The first 6 rows are databound and the last three I created including the checkbox column.  The idea is to present information to the user on page load by populating the gridview with a stored procedure that has a variable passed in a query string (this part works fine) then the user will confirm the information they see by clicking the checkbox in that row.

<asp:GridView ID="gv_advisor" visible="true" runat="server" 
                    AutoGenerateColumns="False" BorderWidth="1px" BackColor="White" GridLines="Both"
                    CellPadding="4" BorderStyle="Solid" BorderColor="#DEDFDE" ForeColor="#006699"
                    AllowSorting="False">
                    <FooterStyle BackColor="#006699"></FooterStyle>
                    <PagerStyle ForeColor="White" HorizontalAlign="Right" BackColor="#F7F7DE"></PagerStyle>
                    <HeaderStyle ForeColor="White" Font-Bold="True" BackColor="#006699"></HeaderStyle>
                    <AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
                    
                     <Columns>

                        <asp:TemplateField HeaderText="Advisor ID" itemstyle-cssclass="hiddencol">
                            <ItemTemplate>
                                <asp:Label  runat="server" ID="advisorid" Text='<%# Eval("ADVISOR_ID") %>' />
                            </ItemTemplate>
                            <ItemStyle VerticalAlign="Middle" />
                
                            <ItemStyle VerticalAlign="Top" />
                        </asp:TemplateField>

                           <asp:TemplateField HeaderText="Plan ID">
                            <ItemTemplate>
                                <asp:Label runat="server" ID="planid" Text='<%# Eval("PLAN_ID") %>' />
                            </ItemTemplate>
                            <ItemStyle VerticalAlign="Middle" />
                           
                            <ItemStyle VerticalAlign="Top" />
                        </asp:TemplateField>

                        <asp:TemplateField HeaderText="Plan Name">
                            <ItemTemplate>
                                <asp:Label runat="server" ID="planname" Text='<%# Eval("PLAN_NAME") %>' />
                            </ItemTemplate>
                            <ItemStyle VerticalAlign="Middle" />
                            
                            <ItemStyle VerticalAlign="Top" />
                        </asp:TemplateField>

                        <asp:TemplateField HeaderText="First Name">
                            <ItemTemplate>
                                <asp:Label runat="server" ID="advisorfirst" Text='<%# Eval("First") %>' />
                            </ItemTemplate>
                            <ItemStyle VerticalAlign="Middle" />
                           
                            <ItemStyle VerticalAlign="Top" />

                        </asp:TemplateField>
                         <asp:TemplateField HeaderText="Last Name">
                            <ItemTemplate>
                                <asp:Label runat="server" ID="advisorlast" Text='<%# Eval("Last") %>' />
                            </ItemTemplate>
                            <ItemStyle VerticalAlign="Middle" />
                            
                            <ItemStyle VerticalAlign="Top" />
                        </asp:TemplateField>

                           <asp:TemplateField HeaderText="Firm Name">
                            <ItemTemplate>
                                <asp:Label runat="server" ID="firmname" Text='<%# Eval("ADVISOR_FIRM_NAME") %>' />
                            </ItemTemplate>
                            <ItemStyle VerticalAlign="Middle" />
                       
                            <ItemStyle VerticalAlign="Top" />
                        </asp:TemplateField>

                           <asp:TemplateField HeaderText="Correct As Is">
                            <ItemTemplate>
                                <asp:Checkbox runat="server" ID="chkUseContact" />
                            </ItemTemplate>
                            <ItemStyle VerticalAlign="Middle" />
                          
                            <ItemStyle VerticalAlign="Middle" />
                        </asp:TemplateField>

                          <asp:TemplateField HeaderText="Alt Contact First">
                            <ItemTemplate>
                                <asp:textbox runat="server" ID="txt_NewContact_First" />
                            </ItemTemplate>
                            <ItemStyle VerticalAlign="Middle" />
                           
                            <ItemStyle VerticalAlign="Middle" />
                        </asp:TemplateField>

                         <asp:TemplateField HeaderText="Alt Contact Last">
                            <ItemTemplate>
                                <asp:textbox runat="server" ID="txt_NewContact_Last" />
                            </ItemTemplate>
                            <ItemStyle VerticalAlign="Middle" />
                     
                            <ItemStyle VerticalAlign="Middle" />
                        </asp:TemplateField>

                        </Columns> 
                    </asp:GridView>

Open in new window


Here is the code that makes the call to the stored procedure on page load to populate the gridview:

      Dim advisoremail as String

      advisoremail = "hard_coded_string_fortesting@testing.com" 

        GetAdvisorList(advisoremail)

Open in new window


Finally here is the function that pulls in the data from a SQL server:

    Public Function GetAdvisorList(ByVal advisoremail As String) As Data.DataSet

        Try


            Dim cn As String = System.Configuration.ConfigurationManager.ConnectionStrings("Verisight").ConnectionString
            'Dim cn As String = ConfigurationManager.ConnectionStrings("Verisight") '"Server=Triton.Psiad.Loc;Database=pubs;uid=psisql;pwd=news@11;"
            Dim conn As New SqlConnection(cn)
            Dim cmd As New SqlCommand("WC_Get_Advisor_List", conn)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@advisor_email", advisoremail)

            Dim ad As New SqlDataAdapter(cmd)
            Dim ds As New DataSet()
            ad.Fill(ds)

            GetAdvisorList = ds

            'ds.Relations.Add(New DataRelation("Category", ds.Tables(0).Columns("cat_id"), ds.Tables(1).Columns("cat_id"), False))

            gv_advisor.DataSource = ds.Tables(0)
            gv_advisor.DataBind()


        Catch ex As Exception
            GetAdvisorList = Nothing
        End Try


    End Function

Open in new window

0
 

Author Closing Comment

by:pensiongenius
ID: 39172032
Thank you, I thought it would be something simple like this because of my relative novice status in asp.net.

As always good work by the experts.
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question