Results 1 to 20 of 20

Thread: checkbox in gridview (updatepanel)

  1. #1

    Thread Starter
    Frenzied Member met0555's Avatar
    Join Date
    Jul 2006
    Posts
    1,385

    checkbox in gridview (updatepanel)

    Hi,

    I have a grdiview with checkbox both are in an updatepanel.
    What i'm trying to do is whenever a checkbox is clicked i want my labelbox to show +1 and when it's unchecked i want to show -1 .
    The problem i'm having is i can't access that check box, it doesn't recognized it when i start writing checkbox2 ...... my code looks like this :


    vb Code:
    1. <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    2.                    <ContentTemplate>
    3.                 <asp:GridView ID="GridView1" runat="server" AllowPaging="True"    OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"
    4.                           onrowupdating="GridView1_RowUpdating"
    5.                           onrowcancelingedit="GridView1_RowCancelingEdit"
    6.                     AllowSorting="True"     AutoGenerateColumns="False" DataKeyNames="ID" PageSize="20"
    7.                     style="font-size: 7pt; font-family: Tahoma" UseAccessibleHeader="False">
    8.                     <Columns>
    9.                      <asp:TemplateField ShowHeader="False">
    10.                 <ItemTemplate>
    11.                  <asp:CheckBox ID="CheckBox2" runat="server" />
    12.            </ItemTemplate>
    13.             </asp:TemplateField>
    14.                         <asp:CommandField CancelText="C" DeleteText="D" EditText="E" InsertText="I"
    15.                             NewText="N" SelectText="S" ShowDeleteButton="True" ShowEditButton="True"
    16.                             UpdateText="U"  />
    17.                  
    18.  
    19.  
    20.                       <asp:TemplateField HeaderText="ID" Visible="False">
    21.            <EditItemTemplate>
    22.             <asp:TextBox ID="textID2" runat="server" Text='<%# Bind("ID") %>' Width="28" Font-Size="8" Font-Names="tahoma" Enabled="False"></asp:TextBox>
    23.                 </EditItemTemplate>
    24.                 <ItemTemplate>
    25.                     <asp:Label ID="Label15" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
    26.                 </ItemTemplate>
    27.             </asp:TemplateField>
    28. .....



    thanks

  2. #2
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: checkbox in gridview (updatepanel)

    Hello,

    The reason that it doesn't like it is because CheckBox2 doesn't actually exist

    What I mean by that is, within the ItemTemplate for the definition of what makes up the GridView CheckBox2 does exist, however, only in the Template. When the GridView renders to the HTML which is sent to the page, there will actually be lots of CheckBoxes, not just one. As a result, you can't directly access the "one" CheckBox that exists in the ItemTemplate.

    Does that make sense?

    In order to "fix" this problem you can do one of two things.

    During the RowDataBound event of the GridView you can inspect the contents of the row, and using the FindControl method you can find the instance of the CheckBox for the given row. Once you have that reference you can either assign a JavaScript function to the click event of the CheckBox and do the work of adding +1 or -1 to the screen, or you can assign a Server Side method to the Click event of the CheckBox so that when clicked, the part of the page in the UpdatePanel goes back to the server and takes the necessary action.

    Hope that makes sense!

    Gary

  3. #3
    Learning .Net danasegarane's Avatar
    Join Date
    Aug 2004
    Location
    VBForums
    Posts
    5,853

    Re: checkbox in gridview (updatepanel)

    Here comes Jquery for Help. You need to use the css for counting the checkbox count.

    Sample

    Code:
    <html>
    <head>
    <script src="http://code.jquery.com/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script type="text/javascript" >
         function getCount()
    {
         var chkboxes=$(" .chkbox"); //Get all the checkboxes
         var checkedCount = chkboxes.filter(":checked").length; //get the checkedcount
         alert(checkedCount);
    }
    
    $(document).ready(function(){
    
    $(" .chkbox").each(function() {
     
                $(this).change(function(){
                    getCount();
                });
            });
    });
    
    </script>
    
    
    
    
    </head>
    <body >
    
    
    
    <input type="text" class="total" />
    <input type="checkbox" class="chkbox" />
    <input type="checkbox" class="chkbox" />
    
    
    
    </body >
    
    </html>
    Please mark you thread resolved using the Thread Tools as shown

  4. #4

    Thread Starter
    Frenzied Member met0555's Avatar
    Join Date
    Jul 2006
    Posts
    1,385

    Re: checkbox in gridview (updatepanel)

    Hi,

    I tried to use the code you provided me, and it works fine but not with my checkboxes in my gridview.

    i also tried to make it work like this, but it seems its not working i don't know what im missing

    vb Code:
    1. Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    2.         '  Dim GridView1 As GridView = CType(sender, GridView)
    3.         Dim atLeastOneRowDeleted As Boolean = False ' Iterate through the Products.Rows property
    4.         Label38.Text = 0
    5.         Dim a, b As String
    6.         For Each row As GridViewRow In GridView1.Rows
    7.             Dim cb As CheckBox = row.FindControl("CheckBox2")
    8.             If cb IsNot Nothing AndAlso cb.Checked Then
    9.  
    10.                 atLeastOneRowDeleted = True
    11.                 Dim ID As Integer = (GridView1.DataKeys(row.RowIndex).Value)
    12.  
    13.                 a += 1
    14.                 b += ID & " "
    15.  
    16.             End If
    17.         Next
    18.         If a > 11 Then
    19.             Label38.Text = b
    20.             Label38.ForeColor = Drawing.Color.Red
    21.         End If
    22.  
    23.  
    24.     End Sub

    t
    hx

  5. #5
    Learning .Net danasegarane's Avatar
    Join Date
    Aug 2004
    Location
    VBForums
    Posts
    5,853

    Re: checkbox in gridview (updatepanel)

    Quote Originally Posted by met0555 View Post
    Hi,

    I tried to use the code you provided me, and it works fine but not with my checkboxes in my gridview.

    i also tried to make it work like this, but it seems its not working i don't know what im missing

    vb Code:
    1. Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    2.         '  Dim GridView1 As GridView = CType(sender, GridView)
    3.         Dim atLeastOneRowDeleted As Boolean = False ' Iterate through the Products.Rows property
    4.         Label38.Text = 0
    5.         Dim a, b As String
    6.         For Each row As GridViewRow In GridView1.Rows
    7.             Dim cb As CheckBox = row.FindControl("CheckBox2")
    8.             If cb IsNot Nothing AndAlso cb.Checked Then
    9.  
    10.                 atLeastOneRowDeleted = True
    11.                 Dim ID As Integer = (GridView1.DataKeys(row.RowIndex).Value)
    12.  
    13.                 a += 1
    14.                 b += ID & " "
    15.  
    16.             End If
    17.         Next
    18.         If a > 11 Then
    19.             Label38.Text = b
    20.             Label38.ForeColor = Drawing.Color.Red
    21.         End If
    22.  
    23.  
    24.     End Sub

    t
    hx

    Where is the code to count ?
    Please mark you thread resolved using the Thread Tools as shown

  6. #6

    Thread Starter
    Frenzied Member met0555's Avatar
    Join Date
    Jul 2006
    Posts
    1,385

    Re: checkbox in gridview (updatepanel)

    vb Code:
    1. <script src="http://code.jquery.com/jquery-1.6.2.min.js" type="text/javascript"></script>
    2. <script type="text/javascript" >
    3.      function getCount()
    4. {
    5.      var chkboxes=$(" .checkbox2"); //Get all the checkboxes
    6.      var checkedCount = chkboxes.filter(":checked").length; //get the checkedcount
    7.      alert(checkedCount);
    8. }
    9.  
    10. $(document).ready(function(){
    11.  
    12. $(" .checkbox2").each(function() {
    13.  
    14.             $(this).change(function(){
    15.                 getCount();
    16.             });
    17.         });
    18. });
    19.  
    20. </script>

  7. #7
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: checkbox in gridview (updatepanel)

    Quote Originally Posted by met0555 View Post
    i also tried to make it work like this, but it seems its not working i don't know what im missing
    Rather than simply saying that something isn't working, it would be better if you could explain exactly why it isn't working. Are there any errors, either on the client side or the server side? If so, what are they? Have you set breakpoints in your code and began stepping through the code? Does it do anything that you are not expecting? If so, what?

    Gary

  8. #8
    Learning .Net danasegarane's Avatar
    Join Date
    Aug 2004
    Location
    VBForums
    Posts
    5,853

    Re: checkbox in gridview (updatepanel)

    Quote Originally Posted by met0555 View Post
    vb Code:
    1. <script src="http://code.jquery.com/jquery-1.6.2.min.js" type="text/javascript"></script>
    2. <script type="text/javascript" >
    3.      function getCount()
    4. {
    5.      var chkboxes=$(" .checkbox2"); //Get all the checkboxes
    6.      var checkedCount = chkboxes.filter(":checked").length; //get the checkedcount
    7.      alert(checkedCount);
    8. }
    9.  
    10. $(document).ready(function(){
    11.  
    12. $(" .checkbox2").each(function() {
    13.  
    14.             $(this).change(function(){
    15.                 getCount();
    16.             });
    17.         });
    18. });
    19.  
    20. </script>


    Did you apply the css checkbox2 to each checkbox in design view ?
    Please mark you thread resolved using the Thread Tools as shown

  9. #9
    Frenzied Member
    Join Date
    Jul 2005
    Posts
    1,168

    Re: checkbox in gridview (updatepanel)

    gep13: Is there a way to create an event handler for a checkbox inside a datagrid?

    met0555: I'm assuming that the labelbox is also within the gridview, and each row has one? If so, try this code inside the Page_Load():

    Code:
    protected void Page_Load(object sender, EventArgs e)
            {
                if (Page.IsPostBack)
                {
                    int count = GridView1.Rows.Count;
                    for (int i = 0; i < count; i++)
                    {
                        CheckBox cb = (CheckBox)GridView1.Rows[i].FindControl("CheckBox2");
                        if (cb.Checked)
                        {
                            Label lbl = (Label)GridView1.Rows[i].FindControl("LabelBox");//i'm assuming this is the ID of your label
                            lbl.Text = "+1";
                        }
                        else
                        {
                            Label lbl = (Label)GridView1.Rows[i].FindControl("LabelBox");
                            lbl.Text = "-1";
                        }
                    }
                }
              
            }
    On your .aspx page, make sure that the CheckBox2 control has AutoPostBack set to True:

    Code:
    <asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="true"/>
    edit: gep13:I noticed you mentioned that you can create a click event on the server side, but I tried that during the "RowDataBound" event, like so:

    Code:
    protected void RowDataBound(object sender, GridViewRowEventArgs e)
            {
    
                CheckBox cb = (CheckBox)e.Row.FindControl("CheckBox2");
                if (cb != null)
                {
                    cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
                }
            }
    It went through the code including the setting of the event handler, but when I finally clicked on a checkbox, it did not trigger the cb_CheckedChanged event. Am I missing something in the code behind or in the aspx page?
    Last edited by benmartin101; Aug 10th, 2011 at 03:22 AM.

  10. #10
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: checkbox in gridview (updatepanel)

    Hello,

    The approach that you are trying is definitely the correct one.

    Have you set a breakpoint on this line:

    Code:
    cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
    Does it actually get run?

    Gary

  11. #11

    Thread Starter
    Frenzied Member met0555's Avatar
    Join Date
    Jul 2006
    Posts
    1,385

    Re: checkbox in gridview (updatepanel)

    Thanks for the helps.

    @benmartin101: with the code you provided for the Page_Load and RowDataBound, it works fine, but if i click on two checkboxes quickly i get error like this one "System.Web.HttpException: The client disconnected. ---> System.Web.UI.ViewStateException: Invalid viewstate." as it server side its slow

    I believe i have to use java or jquery ... to make it fast

    @danasegarane :

    I tried ur code again earlier, and my checkbox code in my gridview looks like this

    Code:
    <asp:CheckBox ID="CheckBox2" runat="server"  class="chkbox" />
    and i don't have to duplicate for each checkbox it will do it auto in gridview.

    and the rest of the code i just copy pasted ur original code. Then when i test it by checking and unchecking the checkboxes i always get a mdgbox with the value of 0.

    (sorry i' new to jquery, but it seems it's my only chance here)


    thanks

  12. #12
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: checkbox in gridview (updatepanel)

    Quote Originally Posted by met0555 View Post
    I believe i have to use java or jquery ... to make it fast
    That really isn't the main reason to use jQuery of JavaScript

  13. #13
    Frenzied Member
    Join Date
    Jul 2005
    Posts
    1,168

    Re: checkbox in gridview (updatepanel)

    Quote Originally Posted by gep13 View Post
    Hello,

    The approach that you are trying is definitely the correct one.

    Have you set a breakpoint on this line:

    Code:
    cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
    Does it actually get run?

    Gary
    Yes, it goes through that line for sure (and it does so multiple times depending on the number of checkboxes generated). cb_CheckedChanged() should handle that event, right?

  14. #14
    Frenzied Member
    Join Date
    Jul 2005
    Posts
    1,168

    Re: checkbox in gridview (updatepanel)

    Quote Originally Posted by met0555 View Post
    Thanks for the helps.

    @benmartin101: with the code you provided for the Page_Load and RowDataBound, it works fine, but if i click on two checkboxes quickly i get error like this one "System.Web.HttpException: The client disconnected. ---> System.Web.UI.ViewStateException: Invalid viewstate." as it server side its slow
    Not sure if this would help, but maybe try setting EnableViewStateMac = "False".

  15. #15
    Frenzied Member
    Join Date
    Jul 2005
    Posts
    1,168

    Re: checkbox in gridview (updatepanel)

    This is weird, but when I add OnCheckedChanged="cb_CheckedChanged" to the aspx page like so:

    Code:
    <ItemTemplate>
                            <asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="true" OnCheckedChanged="cb_CheckedChanged"/>
                        </ItemTemplate>
    It ends up catching that checkedchanged event. But why won't it do it programmatically?
    Last edited by benmartin101; Aug 11th, 2011 at 12:28 AM.

  16. #16
    Frenzied Member
    Join Date
    Jul 2005
    Posts
    1,168

    Re: checkbox in gridview (updatepanel)

    I don't think I can add event handlers during the RowDataBound event. The earliest, I think, I can add event handlers is during the OnRowCreated event - during postback.
    Last edited by benmartin101; Aug 11th, 2011 at 03:32 AM.

  17. #17
    Frenzied Member
    Join Date
    Jul 2005
    Posts
    1,168

    Re: checkbox in gridview (updatepanel)

    Here's new code:

    Code:
    //assign this method on GridView1's OnRowCreated in the aspx page
     protected void RowCreated(object sender, GridViewRowEventArgs e)
            {
                CheckBox cb = (CheckBox)e.Row.FindControl("CheckBox2");
                if (cb != null)
                {
                    cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
                    cb.TabIndex = (short)e.Row.DataItemIndex;
                }
            }
    
            protected void cb_CheckedChanged(object sender, EventArgs e)
            {
                
                CheckBox cb = (CheckBox)sender;
                Label lb = (Label)GridView1.Rows[cb.TabIndex].FindControl("Label1");
                if (lb.Text == "" || lb.Text=="-1")
                {
                    lb.Text = "+1";
                }
                else
                {
                    lb.Text = "-1";
                }
            }
    Don't forget to set AutoPostBack="True".
    Last edited by benmartin101; Aug 11th, 2011 at 03:31 AM.

  18. #18
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: checkbox in gridview (updatepanel)

    Quote Originally Posted by benmartin101 View Post
    I don't think I can add event handlers during the RowDataBound event. The earliest, I think, I can add event handlers is during the OnRowCreated event - during postback.
    Ah, my bad!

    I should have used my own advice and checked here:

    http://msdn.microsoft.com/en-us/library/ms178472.aspx

    You need to create the Event Handler early enough in the Page Life Cycle so that it "sticks" around across Post Backs. Sorry for sending you up the garden path! If I had taken the time to create a sample I would have been able to point you in the right direction

    Gary

  19. #19
    Frenzied Member
    Join Date
    Jul 2005
    Posts
    1,168

    Re: checkbox in gridview (updatepanel)

    Quote Originally Posted by gep13 View Post
    Ah, my bad!

    I should have used my own advice and checked here:

    http://msdn.microsoft.com/en-us/library/ms178472.aspx

    You need to create the Event Handler early enough in the Page Life Cycle so that it "sticks" around across Post Backs. Sorry for sending you up the garden path! If I had taken the time to create a sample I would have been able to point you in the right direction

    Gary
    yeah, i forgot about the Page Life Cycle thing. Still thinking i'm programming in windows form applications.

  20. #20
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: checkbox in gridview (updatepanel)

    Quote Originally Posted by benmartin101 View Post
    yeah, i forgot about the Page Life Cycle thing. Still thinking i'm programming in windows form applications.
    You will get used to it

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width