Using VB.net and ASP.net with dynamic checkboxes to check the checked status within a Gridview where created with a placeholder

ThePrettyGeek
ThePrettyGeek used Ask the Experts™
on
I have a Gridview that pulls data from MySQL and then displays it along side a column of checkboxes that are created via a ItemTemplage in the html. this works wonderfully for creating it but problem lies in checking the status of these check boxes.

I first tried just using the checkbox.checked =  true or false method but because its created dynamically the VB code doesn't see it.

I thought I had figured it out at one pont with the EnabledViewState in the VB code where it checked - if CheckBox IsNot Nothing And CheckBox.EnableViewState = True Then bla bla bla but all that was checking was to see if view state was enabled and it was which would then select all of the items and run the code under the if statment up until the checkbox was ticked. so it was updating all sql entries above the correct one as well.


What I need it to check is still If CheckBox IsNot Nothing And CheckBox.Checked = True Then
but it constantly returns false.

I thought I had found somewhat of an answer with
http://stackoverflow.com/questions/1975548/reading-checked-property-of-dynamic-checkbox-on-page-postback
and other than nameing things a bit differently it may as well have been a direct copy and paste of the code but this too failed. I tried using the CheckChanged and the OnCheckChaned properties but VS didnt recognize them as valid properties of the command,

I thouht there may be someway to use the attributes property and played around with variations of CheckBox.Attributes(ViewState(Checked)) and Im still not convinced Im 100% wrong with going this direction, I just couldnt figure out the exact wording on it.

In any event, Im back here begging for help
' VB.NET Code
Dim tr As TableRow
Dim RowCounter As Integer = 0

For Each tr In GridViewID.Rows
  Dim cb As CheckBox = GridViewID.Rows(RowCounter).Cells(0).FindControl("CheckBoxID")
  If cb IsNot Nothing And cb.Checked = True Then
    'Code to pull data from GridViewID and compare to DB
    'Code to Update MySQL Database
    RowCounter = +1
  End If
next




<!--ASP / HTML CODE-->
                <asp:GridView ID="GridViewID" runat="server">
                    <Columns>
                       <asp:TemplateField HeaderText="CheckBox Column">
                        <ItemTemplate>                       
                         <asp:CheckBox runat="server" ID="CheckBoxID" Checked="false" EnableViewState="true" />                                            
                        </ItemTemplate>
                       </asp:TemplateField>
                    </Columns>
                </asp:GridView>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Please remove Checked="false" code from ASPX page and try to handle it from the code.

Author

Commented:
The way I have it set up, the check box is not declared until I press the delete button and then its declared for each line in the Grid View. I tried just leaving it out of the aspx but it still returns false every time.

Now the delete button is not actually deleting anything from the database its simpy updating the record with a field that says its deleted and the date it was deleted. This allows me to keep track of the records that where deleted and but when the dataset repopulates it only looks for those records who are false in the deleted field.

so the button declares the check box as a row/cell/find control
then runs the if statement to seeif it isnot nothing and if it is checked or not

this is where it always returns false even if it isnt false

Author

Commented:
Ok Ive tried moving where I declaired the checkbox and put it in its own sub and also putting it in the load page sub with no luck. I still always end up with the checked property staying false.
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

nekkantisurendraSoftware Engineer

Commented:
Hi,
   
     From the VB code when you are lopping through the grid rows are you able to access other row values from the grid?

Author

Commented:
Yes I am and I woujld be willing to use the boolean field that the checkbox updates to represent the value if I could get it to show up as a checkbox and not a string that says true or false but either way I need to be able to check the checkbox and then do an action on the row.
For Each tr In GridViewID.Rows
  Dim cb As CheckBox = GridViewID.Rows(RowCounter).Cells(0).FindControl("CheckBoxID") <-- Row counter will increase only if the row is checked.
  If cb IsNot Nothing And cb.Checked = True Then
    'Code to pull data from GridViewID and compare to DB
    'Code to Update MySQL Database
    RowCounter = +1
  End If
next

Why dont you do like this. This should loop through all the rows.

For Each tr In GridViewID.Rows
  Dim cb As CheckBox = tr .Cells(0).FindControl("CheckBoxID")
  If cb IsNot Nothing And cb.Checked = True Then
    'Code to pull data from GridViewID and compare to DB
    'Code to Update MySQL Database
    End If
next

let us know if this is still an issue.

Author

Commented:
Nope, it is still saying that the checkboxes are false.

I added a messagebox under the for each statement which gives performs simply msgbox(convert.tostrting(cb.checked)) and for each line it returns false wether its checked or not.

I also simplified the equation and tried making the if statement just if cb.checked = true but there was not difference there either.

For some reason its just not reporting the checkboxes checked status
And also shouldn't the find control be like this

Tr.findcontrol("checkboxid"$
And also shouldn't the find control be like this

Tr.findcontrol("checkboxid")

Author

Commented:
I changed it but it still returns false on every line.

Author

Commented:
Here is the actual code for the top of the sub. Ignore all of the commented out stuff, its from past failed attempts.

    Sub DeleteOffice()
        ' Dim dt As DataTable 'requires  system.data to be imported
        Dim SomethingToDelete As Boolean = False
        Dim TestString As String = ""
        Dim tr As TableRow
        For Each tr In GVShowData.Rows
            '    cb = GVShowData.Rows(RowCounter).Cells(0).FindControl("chkDeleteOffice")
            Dim cb As CheckBox = tr.FindControl("chkDeleteOffice")

            'cb.AutoPostBack = True
            ' AddHandler cb.CheckedChanged, AddressOf cb_CheckedChanged
            ' Me.Form.Controls.Add(cb)

            'cb.ID = "chkOfficeDeleted"
            'cb.EnableViewState = True
            ' AddHandler cb.Checked, AddressOf cb_Checked
            ' cb.Attributes(ViewState(Checked))
            MsgBox("About to perform If Statement: cb.cheked=" & Convert.ToString(cb.Checked))
            'If cb IsNot Nothing And cb.Checked = True Then
            If cb.Checked = True Then
                MsgBox(Convert.ToString(cb.Checked))



Here is the actual code of the gridview in the aspx file.
The two databoud items are there for testing purposes
   
                <asp:GridView ID="GVShowData" runat="server">
                    <Columns>
                       <asp:TemplateField HeaderText="Delete Office">
                        <ItemTemplate>                    
                                 <asp:CheckBox ID="chkDeleteOffice" runat="server" enabled="true" />                                                
                        </ItemTemplate>

                       </asp:TemplateField>
                       
                       <asp:BoundField DataField="Date" DataFormatString="{0:d}" HtmlEncode="false" />
                       <asp:BoundField DataField="WorkDone" />
                       
                       
                    </Columns>
                </asp:GridView>
Try tr As GridViewRow instead of TableRow

Author

Commented:
Unfortunately that didn't work either. I'm going to have to hire someone who will let me pull their hair out soon because I don't know if I'm going to have any left soon.

I think I tried that once before but Im not sure.
That's how I normally do. May be there is something I am missing out.

Author

Commented:
Ill post the entire project for the time being at http:www.cristinarush.com/SS.rar
Ill take it down before I close this issue out.

Cristy

Author

Commented:
Ok I deleted the link and rewrote the code in a new project and Im having the same issue.
The vb code and aspx code are in two different code snippets bellow. This is the full code of the test project. Its very small and easy to look at.


<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>GridViewWithCheckBoxesTestSite</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>    
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField HeaderText="Checked?">
                    <ItemTemplate>
                        <asp:CheckBox ID="chkChecked" runat="server" enabled="true" />
                    </ItemTemplate>
                </asp:TemplateField>     
                
                <asp:BoundField DataField="Date" HeaderText="Date" DataFormatString="{0:d}" HtmlEncode="false" />
                <asp:BoundField DataField="Name" HeaderText="Name" HtmlEncode="false" />
                         
            </Columns>
        </asp:GridView>
    </div>
    <asp:Button ID="btnDelete" runat="server" Text="Delete and Update" />
    </form>
</body>
</html>

Open in new window

Imports MySql.Data.MySqlClient
Imports System.Data.SqlClient
Imports System.IO
Imports System.Data
Partial Class _Default
    Inherits System.Web.UI.Page
    Dim con As New MySqlConnection
    Dim ds As New Data.DataSet



    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        GetData()
        MsgBox("test")
    End Sub

    Sub DBConnect()
        con.ConnectionString = "data source=server1 ; database=status; uid=root; Password=UndisclosedPassword;"
        con.Open()
    End Sub

    Sub DBClose()
        con.Close()
        con.Dispose()
    End Sub

    Sub GetData()
        GridView1.DataSource = ""
        ds.Clear()
        DBConnect()
        Dim GetDataDataAdapter As New MySqlDataAdapter("Select Date, Name From transaction", con)
        GetDataDataAdapter.Fill(ds, "transaction")
        GridView1.DataSource = ds.Tables("transaction")
        GridView1.DataBind()
        DBClose()
    End Sub

    Sub CheckForCheckMark()
        Dim RowCounter As Integer = 0
        Dim tr As GridViewRow
        For Each tr In GridView1.Rows
            Dim cb As CheckBox = tr.FindControl("chkChecked")
            ' MsgBox(Convert.ToString(cb.Checked))
            If cb.Checked = True Then
                MsgBox("Row " & RowCounter & "is checked!")
            Else
                MsgBox("Row " & RowCounter & "is not checked!")
            End If
            RowCounter = RowCounter + 1
        Next
        RowCounter = 0
    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        CheckForCheckMark()
    End Sub
End Class

Open in new window

Ok here is the issue from you code from zipped project.


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load



        'If Session("UName") = "" Then
        '    Session("SpecialMessage") = "You must first login before Entering your work"
        '    Response.Redirect("./logout.aspx")

        'Else

        lblUserName.Text = "Logged in as: " & "sree"
        lbl1.Text = "<a href=./Default.aspx>Home</font></a>"
        lbl2.Text = "<a href=./logout.aspx>Log Out</a>"
        lbl3.Text = "<a href=./reporting.aspx>Reports</a>"
        lbl4.Text = "<a href=./settings.aspx>Settings</a>"
        lbl5.Text = "<a href=./WorkDone.aspx><font color=000000>Add Offices</font></a>"
        ExtraTab1.Visible = True
        '  End If

        lblUserName.Text = "Logged in as: " & "sree"
        If Not IsPostBack Then
            calSubmissionDate.SelectedDate = Today
            ReadSettingsFile()
            GetUserDataforToday()
        End If

        '   GetUserDataforToday()  <-- When you click the delete button the page gets reloaded again. At this point you are not supposed to load the grid again as it clears off the your check box selections. This needs to be commented out and you are doing right having this method in Not Ispostback condition.


    End Sub

In you new code

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 If Not IsPostBack Then
        GetData() <-- This should be in this condition.
End If
        MsgBox("test")
    End Sub

Try it out. I tried and worked fine with your zipped project.

Author

Commented:
Thank you soooooooo much. I knew it was something stupid simple I was missing and I didnt even think about the page reloading when the button was clicked and it re-retrieving the data.

Just a note I also had to add the getdata() to the end of the deleteoffice sub to refresh the datagrid after it was deleted, before I was relying on the one in the page_load. Thats actually why it was there in page_load

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial