Solved

Checkbox in gridview value not recognized on submit

Posted on 2013-05-15
7
560 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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

747 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now