Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Checkbox in gridview value not recognized on submit

Posted on 2013-05-15
7
Medium Priority
?
582 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 2000 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
Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

 
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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…

824 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