Solved

How to add checkbox event handler in gridview

Posted on 2014-12-05
8
300 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 

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
 
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

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

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

Suggested Solutions

Developer tools in browsers have been around for a while, yet they are still heavily underused by developers. Developers still fix html or CSS then refresh page to see effect, or they put alert or debugger in JavaScript and then try again and again …
Thoughout my experience working on eCommerce web applications I have seen applications succumbing to increased user demand and throughput. With increased loads the response times started to spike, which leads to user frustration and lost sales. I ha…
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…
Learn how to set-up PayPal payment integration in your Wufoo form. Allow your users to remit payment through PayPal upon completion of your online form. This is helpful for collecting membership payments, customer payments, donations, and more.

839 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