Avatar of ThePrettyGeek
ThePrettyGeekFlag for United States of America

asked on 

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

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

.NET ProgrammingASP.NET

Avatar of undefined
Last Comment
ThePrettyGeek
Avatar of Rahul Agarwal
Rahul Agarwal
Flag of India image

Please remove Checked="false" code from ASPX page and try to handle it from the code.
Avatar of ThePrettyGeek
ThePrettyGeek
Flag of United States of America image

ASKER

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
Avatar of ThePrettyGeek
ThePrettyGeek
Flag of United States of America image

ASKER

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.
Hi,
   
     From the VB code when you are lopping through the grid rows are you able to access other row values from the grid?
Avatar of ThePrettyGeek
ThePrettyGeek
Flag of United States of America image

ASKER

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.
Avatar of srikanthreddyn143
srikanthreddyn143

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.
Avatar of ThePrettyGeek
ThePrettyGeek
Flag of United States of America image

ASKER

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")
Avatar of ThePrettyGeek
ThePrettyGeek
Flag of United States of America image

ASKER

I changed it but it still returns false on every line.
Avatar of ThePrettyGeek
ThePrettyGeek
Flag of United States of America image

ASKER

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
Avatar of ThePrettyGeek
ThePrettyGeek
Flag of United States of America image

ASKER

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.
Avatar of ThePrettyGeek
ThePrettyGeek
Flag of United States of America image

ASKER

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
Avatar of ThePrettyGeek
ThePrettyGeek
Flag of United States of America image

ASKER

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

ASKER CERTIFIED SOLUTION
Avatar of srikanthreddyn143
srikanthreddyn143

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of ThePrettyGeek
ThePrettyGeek
Flag of United States of America image

ASKER

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
.NET Programming
.NET Programming

The .NET Framework is not specific to any one programming language; rather, it includes a library of functions that allows developers to rapidly build applications. Several supported languages include C#, VB.NET, C++ or ASP.NET.

137K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo