Solved

How to add checkbox event handler in gridview

Posted on 2014-12-05
8
297 Views
Last Modified: 2014-12-26
I have an ASP.net 3.5 web application with a databound gridview in an ASCX page. I want to add an oncheckedchanged event to a checkbox in the gridview. I have tried some things but with no success.

Here is the simplified gridview:
<asp:GridView ID="grdStaff" runat="server" EnableModelValidation="True" Font-Names="Arial" Font-Size="X-Small" ForeColor="#333333" AutoGenerateColumns="False" DataKeyNames="StaffID" Width="695px" AlternatingRowStyle-BackColor="White">

        <asp:TemplateField ControlStyle-Width="30px" FooterStyle-Width="30px" HeaderStyle-Width="30px" ItemStyle-Width="30px" HeaderText="Left?">
            <HeaderTemplate>
                <asp:Label runat="server" ID="HeaderLevelCheckBox" Text="Left?" />
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox runat="server" ID="chkLeft" AutoPostBack="True" OnCheckedChanged="chkLeft_OnCheckedChanged"/>
            </ItemTemplate>
        </asp:TemplateField>

here is the event handler in code behind:
 Public Sub chkLeft_OnCheckedChanged(sender As Object, e As EventArgs)
'do some stuff here
        End Sub

however when I build the project I see the following error:
Error      80      'chkLeft_OnCheckedChanged' is not a member of 'ASP.pages_skins_default_staff_editstaffing_ascx'.

Can anybody help with this please? I'm sure I'm missing something really simple.
0
Comment
Question by:Al230762
  • 5
  • 3
8 Comments
 
LVL 28

Expert Comment

by:sammySeltzer
ID: 40484586
What exactly are you trying to do?
0
 

Author Comment

by:Al230762
ID: 40484622
I am trying to update the row's record in the database when the user checks or unchecks the checkbox. There would be a conformation message too.  I don't want the user to have to click the Edit button first before updating the checkbox data although there is an Edit and a Delete button on each row.
0
 
LVL 28

Expert Comment

by:sammySeltzer
ID: 40484639
This is how I use onCheckChanged event.

See if you can adapt for your needs:

Public Partial Class _Default
    Inherits System.Web.UI.Page
    Dim constr As String = ConfigurationManager.ConnectionStrings("conStr").ConnectionString
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        If Not Page.IsPostBack Then
            LoadData()
        End If
    End Sub


    Private Sub getData()

        Dim query As String = "SELECT StaffID, StaffName, FieldToBeUpdate FROM yourTable"

        Dim da As New SqlDataAdapter(query, constr)
        Dim table As New DataTable()
        da.Fill(table)

        grdStaff.DataSource = table
        grdStaff.DataBind()
    End Sub

    Public Sub chkLeft_OnCheckedChanged(sender As Object, e As EventArgs)
        Dim chkLeft As CheckBox = DirectCast(sender, CheckBox)
        Dim row As GridViewRow = DirectCast(chkLeft.NamingContainer, GridViewRow)


        Dim cid As String = row.Cells(1).Text
      '  Dim status As Boolean = chkLeft.Checked Use this if you are using bit data type

        Dim query As String = "UPDATE yourTable SET FieldToBeUpdate = @FieldToBeUpdate WHERE StaffID = @StaffID"

        Dim con As New SqlConnection(constr)
        Dim com As New SqlCommand(query, con)


        com.Parameters.Add("@FieldToBeUpdate", SqlDbType.nvarchar).Value = FieldToBeUpdate
        com.Parameters.Add("@StaffID", SqlDbType.Int).Value = StaffID


        con.Open()
        com.ExecuteNonQuery()
        con.Close()

        getData()
    End Sub
End Class

Open in new window


Markup:

<body>
    <form id="form1" runat="server">
    <asp:GridView ID="grdStaff" runat="server" AutoGenerateColumns="False"
    BackColor="White" BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"  
    CellPadding="0" CellSpacing="0" DataKeyNames="StaffID" Font-Size="10"
    Font-Names="Arial" GridLines="Vertical" Width="40%">
           
            <Columns>            
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="chkLeft" runat="server"
                            AutoPostBack="true" OnCheckedChanged="chkLeft_OnCheckedChanged"
                            Checked='<%# Eval("fieldNameToBeUpdated") %>'
                            Text='<%# Eval("fieldNameToBeUpdated").ToString().Equals("True") ? " Updated " : " Reversed " %>' />
                    </ItemTemplate>                   
                </asp:TemplateField>
               
            </Columns>
           
    <HeaderStyle BackColor="#336699" ForeColor="White" Height="20" />
          
</asp:GridView>
    </form>
</body>

Open in new window

0
 

Author Comment

by:Al230762
ID: 40484662
Here's what I have:

Protected Sub Page_Load(sender As Object, e As EventArgs)
        If Not Page.IsPostBack Then
            LoadStaff()
        End If
    End Sub



Sub LoadStaff()
            cmd = GetCommand("spStaffSELECT")
            cmd.Parameters("@gettype").Value = 3
            cmd.Parameters("@companyID").Value = SessionProperties.Security.companyID
            Dim DsStaff As DataSet = ConvertDataReaderToDataSet(cmd.ExecuteReader)

            If DsStaff.Tables(0).Rows.Count > 0 Then
                grdStaff.DataSource = DsStaff
                grdStaff.DataBind()
            End If
        End Sub


Public Sub chkLeft_OnCheckedChanged(sender As Object, e As EventArgs)
 'update record in database
End Sub


Gridview in ASCX page:

 <asp:GridView ID="grdStaff" runat="server" EnableModelValidation="True" Font-Names="Arial" Font-Size="X-Small" ForeColor="#333333" AutoGenerateColumns="False" DataKeyNames="StaffID" Width="695px" AlternatingRowStyle-BackColor="White">

         <asp:TemplateField ControlStyle-Width="30px" FooterStyle-Width="30px" HeaderStyle-Width="30px" ItemStyle-Width="30px" HeaderText="Left?">
             <HeaderTemplate>
                 <asp:Label runat="server" ID="HeaderLevelCheckBox" Text="Left?" />
             </HeaderTemplate>
             <ItemTemplate>
                 <asp:CheckBox runat="server" ID="chkLeft" AutoPostBack="True" OnCheckedChanged="chkLeft_OnCheckedChanged"/>
             </ItemTemplate>
         </asp:TemplateField>

still seeing the error:
Error      80      'chkLeft_OnCheckedChanged' is not a member of 'ASP.pages_skins_default_staff_editstaffing_ascx'.

Any idea what I'm missing here?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 28

Expert Comment

by:sammySeltzer
ID: 40485001
You have a user control called pages_skins_default_staff_editstaffing_ascx.

How is that connected to your gridview markup?
0
 

Author Comment

by:Al230762
ID: 40485281
The grid view is in an ASCX page at location pages\skins\default\staff\EditStaffing.ascx
We use ASPX pages with MasterPage and ASCX controls with code behind.
0
 

Accepted Solution

by:
Al230762 earned 0 total points
ID: 40511930
I needed to put the event code in the ASCX page itself rather than in code-behind. Thanks anyway for trying to help.
0
 

Author Closing Comment

by:Al230762
ID: 40518278
I found the solution myself and none of the previous suggestions helped with that to be honest.
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

Using Quotation Marks in PHP This question (http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28217211.html) seems to come up a lot for developers who are new to PHP.  And it got me thinking, "How can we explain the rule…
Foolproof security solutions has become one of the key necessities of every e-commerce or Internet banking website. If you too own an online shopping site then its vital for you to equip your web portal with customer security features that can allow…
This video teaches viewers how to create their own website using cPanel and Wordpress. Tutorial walks users through how to set up their own domain name from tools like Domain Registrar, Hosting Account, and Wordpress. More specifically, the order in…
Use Wufoo, an online form creation tool, to make powerful forms. Learn how to choose which pages of your form are visible to your users based on their inputs. The page rules feature provides you with an opportunity to create if:then statements for y…

707 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

16 Experts available now in Live!

Get 1:1 Help Now