Solved

How to add checkbox event handler in gridview

Posted on 2014-12-05
8
298 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Json and asp.net mvc 2 44
Data is not showing from images 15 37
ASP.NET 5 Templates 2 65
Ajax Panel Not Updating When Triggered By Timer 4 37
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
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 custom confirmation messages to users who complete your Wufoo form. Include inputs from fields in your form, webpage redirects, and more with Wufoo’s confirmation options.

911 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

19 Experts available now in Live!

Get 1:1 Help Now