4

Note: I've updated the code for this question to make the example a bit clearer and leverages the sample code provided by Karl Anderson below. I am also open to other ways of getting what I need to accomplish finalized.

I'm in the process of creating a form which includes multiple check boxes that may or may not be leveraged for each request. I'm attempting to create a button below these checkboxes in the DetailsView grid that will only check (as opposed to a button that will check and uncheck) the boxes if the need to check them all arises. As you can see from the code below that there are multiple text boxes/BoundFields surrounding the checkboxes that hold various types of information for this form. The form without the added complexity of the 'check all checkboxes' button works without any issues on the frontend and when writing to the database.

Using the code below the current hurdle I'm facing is not only getting the button to only check all the checkboxes at once, but getting past this error when the page loads:

Cannot convert type 'System.Web.UI.WebControls.TableCell' to 'System.Web.UI.WebControls.CheckBox' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

From my research into similar (but not exact) errors, I need to convert the checkboxes into some other form. I've never faced this scenario before and I'm pulling my hair out not only looking for educational references but some sort of pointer on how to resolve not only the conversion portion but accurate and current (within the last few years) references on how I can resolve the bigger issue of the button correctly checking all 19 checkboxes.

What am I doing wrong here and is this the correct way to get the results I want doe a DetailsView? I'd not only like to learn how to resolve this but also learn the theory/logic behind this challenge so I can learn it the right way.

aspx code.

(Note some cosmetic code for the details view has been omitted)


<%@ Page Title="Test Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="form2.aspx.cs" Inherits="form2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:DetailsView ID="DetailsView" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">
    <AlternatingRowStyle BackColor="White" />
    <insert asp cosmetic gobbledy gook here>
    <Fields>
        <asp:BoundField DataField="Field_1" HeaderText="Ticket Number" SortExpression="Field_1" />
        <asp:BoundField DataField="Field 2" HeaderText="Field 2" SortExpression="Field_2" />
        <asp:BoundField DataField="Field_3" HeaderText="Field 3" SortExpression="Field_3" />
        <asp:BoundField DataField="Field_4" HeaderText="Field 4" SortExpression="Field_4" />
        <asp:BoundField DataField="Field_5" HeaderText="Field 5" SortExpression="Field_5" />
        <asp:BoundField DataField="Field_6" HeaderText="Field 6" SortExpression="Field_6" />
        <asp:BoundField DataField="Field_7" HeaderText="Field 7" SortExpression="Field_7" />
        <asp:BoundField DataField="Field_8" HeaderText="Field 8" SortExpression="Field_8" />
        <asp:BoundField DataField="Field_9" HeaderText="Field 9" SortExpression="Field_9" />
        <asp:BoundField DataField="Field_10" HeaderText="Field 10" SortExpression="Field_10" />
        <asp:CheckBoxField DataField="Check_Box_1" HeaderText="Check Box 1" SortExpression="Check_Box_1" />
        <asp:CheckBoxField DataField="Check_Box_2" HeaderText="Check Box 2" SortExpression="Check_Box_2" />
        <asp:CheckBoxField DataField="Check_Box_3" HeaderText="Check Box 3" SortExpression="Check_Box_3" />
        <asp:CheckBoxField DataField="Check_Box_4" HeaderText="Check Box 4" SortExpression="Check_Box_4" />
        <asp:CheckBoxField DataField="Check_Box_5" HeaderText="Check Box 5" SortExpression="Check_Box_5" />
        <asp:CheckBoxField DataField="Check_Box_6" HeaderText="Check Box 6" SortExpression="Check_Box_6" />
        <asp:CheckBoxField DataField="Check_Box_7" HeaderText="Check Box 7" SortExpression="Check_Box_7" />
        <asp:CheckBoxField DataField="Check_Box_8" HeaderText="Check Box 8" SortExpression="Check_Box_8" />
        <asp:CheckBoxField DataField="Check_Box_9" HeaderText="Check Box 9" SortExpression="Check_Box_9" />
        <asp:CheckBoxField DataField="Check_Box_10" HeaderText="Check Box 10" SortExpression="Check_Box_10" />
        <asp:CheckBoxField DataField="Check_Box_11" HeaderText="Check Box 11" SortExpression="Check_Box_11" />
        <asp:CheckBoxField DataField="Check_Box_12" HeaderText="Check Box 12" SortExpression="Check_Box_12" />
        <asp:CheckBoxField DataField="Check_Box_13" HeaderText="Check Box 13" SortExpression="Check_Box_13" />
        <asp:CheckBoxField DataField="Check_Box_14" HeaderText="Check Box 14" SortExpression="Check_Box_14" />
        <asp:CheckBoxField DataField="Check_Box_15" HeaderText="Check Box 15" SortExpression="Check_Box_15" />
        <asp:CheckBoxField DataField="Check_Box_16" HeaderText="Check Box 16" SortExpression="Check_Box_16" />
        <asp:CheckBoxField DataField="Check_Box_17" HeaderText="Check Box 17" SortExpression="Check_Box_17" />
        <asp:CheckBoxField DataField="Check_Box_18" HeaderText="Check Box 18" SortExpression="Check_Box_18" />
        <asp:CheckBoxField DataField="Check_Box_19" HeaderText="Check Box 19" SortExpression="Check_Box_19" />


        <asp:ButtonField ButtonType="Button" CommandName="btnSelectAll" Text="Select/Check All Servers"


        <asp:BoundField DataField="Field_11" HeaderText="Field 11" SortExpression="Field_11" />
        <asp:BoundField DataField="Field_12" HeaderText="Field 12" SortExpression="Field_12" />
        <asp:BoundField DataField="Field_13" HeaderText="Field 13" SortExpression="Field_13" />

        <asp:CommandField ButtonType="Button" NewText="CreateRecord" ShowInsertButton="True" />
    </Fields>
    <more asp non essential cosmetic gobbledy gook>

        </asp:DetailsView>
        <asp:SqlDataSource ID="SqlDataSource1" ConnectionString="<%$ ConnectionStrings:test_form_connect %>" runat="server" InsertCommand="INSERT INTO [test].[detailsview_test_form] ([Field_1], [Field_2], [Field_3], [Field_4], [Field_5], [Field_6], [Field_7], [Field_8], [Field_9], [Field_10], [Check_Box_1], [Check_Box_2], [Check_Box_3], [Check_Box_4], [Check_Box_5], [Check_Box_6], [Check_Box_7], [Check_Box_8], [Check_Box_9], [Check_Box_10], [Check_Box_11], [Check_Box_12], [Check_Box_13], [Check_Box_14], [Check_Box_15], [Check_Box_16], [Check_Box_17], [Check_Box_18], [Check_Box_19], [Field_11], [Field_12], [Field_13]) VALUES (@Field_1, @Field_2, @Field_3, @Field_4, @Field_5, @Field_6, @Field_7, @Field_8, @Field_9, @Field_10, @Check_Box_1, @Check_Box_2, @Check_Box_3, @Check_Box_4, @Check_Box_5, @Check_Box_6, @Check_Box_7, @Check_Box_8, @Check_Box_9, @Check_Box_10, @Check_Box_11, @Check_Box_12, @Check_Box_13, @Check_Box_14, @Check_Box_15, @Check_Box_16, @Check_Box_17, @Check_Box_18, @Check_Box_19, @Field_11, @Field_12, @Field_13) ">

        <InsertParameters>
    <asp:Parameter Name="Field_1" />
    <asp:Parameter Name="Field_2" />
    <asp:Parameter Name="Field_3" />
    <asp:Parameter Name="Field_4" />
    <asp:Parameter Name="Field_5" />
    <asp:Parameter Name="Field_6" />
    <asp:Parameter Name="Field_7" />
    <asp:Parameter Name="Field_8" />
    <asp:Parameter Name="Field_9" />
    <asp:Parameter Name="Field_10" />
    <asp:Parameter Name="Check_Box_1" />
    <asp:Parameter Name="Check_Box_2" />
    <asp:Parameter Name="Check_Box_3" />
    <asp:Parameter Name="Check_Box_4" />
    <asp:Parameter Name="Check_Box_5" />
    <asp:Parameter Name="Check_Box_6" />
    <asp:Parameter Name="Check_Box_7" />
    <asp:Parameter Name="Check_Box_8" />
    <asp:Parameter Name="Check_Box_9" />
    <asp:Parameter Name="Check_Box_10" />
    <asp:Parameter Name="Check_Box_11" />
    <asp:Parameter Name="Check_Box_12" />
    <asp:Parameter Name="Check_Box_13" />
    <asp:Parameter Name="Check_Box_14" />
    <asp:Parameter Name="Check_Box_15" />
    <asp:Parameter Name="Check_Box_16" />
    <asp:Parameter Name="Check_Box_17" />
    <asp:Parameter Name="Check_Box_18" />
    <asp:Parameter Name="Check_Box_19" />
    <asp:Parameter Name="Field_11" />
    <asp:Parameter Name="Field_12" />
    <asp:Parameter Name="Field_13" />

            </InsertParameters>
            </asp:SqlDataSource>


</asp:Content>

.....and the cs code:

using System;
using System.Configuration;
using System.Collections;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class form2 : System.Web.UI.Page    
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void DetailsView1_ItemCommand(Object sender, DetailsViewCommandEventArgs e)
{
    foreach (Details
        if (e.CommandName == "btnSelectAll")
        {
        DetailsViewRow row = DetailsView1.Rows[9];
        (row.Cells[10] as CheckBox).Checked = true; 
        DetailsViewRow row1 = DetailsView1.Rows[10];
        (row1.Cells[11] as CheckBox).Checked = true;
        DetailsViewRow row2 = DetailsView1.Rows[11];
        (row.Cells[12] as CheckBox).Checked = true;
        DetailsViewRow row3 = DetailsView1.Rows[12];
        (row.Cells[13] as CheckBox).Checked = true;
        DetailsViewRow row4 = DetailsView1.Rows[13];
        (row.Cells[14] as CheckBox).Checked = true;
        DetailsViewRow row5 = DetailsView1.Rows[14];
        (row.Cells[15] as CheckBox).Checked = true;
        DetailsViewRow row6 = DetailsView1.Rows[15];
        (row.Cells[16] as CheckBox).Checked = true;
        DetailsViewRow row7 = DetailsView1.Rows[16];
        (row.Cells[17] as CheckBox).Checked = true;
        DetailsViewRow row8 = DetailsView1.Rows[17];
        (row.Cells[18] as CheckBox).Checked = true;
        DetailsViewRow row9 = DetailsView1.Rows[18];
        (row.Cells[19] as CheckBox).Checked = true;
        DetailsViewRow row10 = DetailsView1.Rows[19];
        (row.Cells[20] as CheckBox).Checked = true;
        DetailsViewRow row11 = DetailsView1.Rows[20];
        (row.Cells[21] as CheckBox).Checked = true;
        DetailsViewRow row12 = DetailsView1.Rows[21];
        (row.Cells[22] as CheckBox).Checked = true;
        DetailsViewRow row13 = DetailsView1.Rows[22];
        (row.Cells[23] as CheckBox).Checked = true;
        DetailsViewRow row14 = DetailsView1.Rows[23];
        (row.Cells[24] as CheckBox).Checked = true;
        DetailsViewRow row15 = DetailsView1.Rows[24];
        (row.Cells[25] as CheckBox).Checked = true;
        DetailsViewRow row16 = DetailsView1.Rows[25];
        (row.Cells[26] as CheckBox).Checked = true;
        DetailsViewRow row17 = DetailsView1.Rows[26];
        (row.Cells[27] as CheckBox).Checked = true;
        DetailsViewRow row18 = DetailsView1.Rows[27];
        (row.Cells[28] as CheckBox).Checked = true;
        DetailsViewRow row19 = DetailsView1.Rows[28];
        (row.Cells[29] as CheckBox).Checked = true;



    }
}   
}
Techie Joe
  • 847
  • 2
  • 14
  • 32

7 Answers7

1

This is untested, but should work so try this:

protected void DetailsView1_ItemCommand(Object sender, DetailsViewCommandEventArgs e)
{
    // Use the CommandName property to determine which button
    // was clicked. 
    if (e.CommandName == "btnSelectAll")
    {
        // You may need to tweak this as I almost never use DetailsView, but the concept should work
        // Check the Apples checkbox
        // Apples is the first row (index 0) and second cell (index 1)
        DetailsViewRow row = DetailsView1.Rows[0];
        (row.Cells[1] as CheckBox).Checked = true;

        // Check the Oranges checkbox
        // Apples is the second row (index 1) and second cell (index 1)
        DetailsViewRow row = DetailsView1.Rows[1];
        (row.Cells[1] as CheckBox).Checked = true;

        // Keep moving through the rows...
    }

}
Karl Anderson
  • 34,606
  • 12
  • 65
  • 80
  • Tried this but it's erroring with the following error "Cannot convert type system.web.ui.webcontrols.tablecell to system.web.ui.webcontrols.checkbox via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion." I'm a little new to Boxing and Unboxing so I'm getting up to speed on how this applies to your answer. – Techie Joe Jul 01 '13 at 19:41
  • What is in `row.Cells[1]`? Like I said this is an untested solution, but the general idea is there for you to try out. Please debug. – Karl Anderson Jul 01 '13 at 20:29
  • Ok I'm stumped. I've got the code inserted into my cs file and got it all working except for this part: "DetailsViewRow row = DetailsView1.Rows[0]; (row.Cells[1] as CheckBox).Checked = true;" as it keeps throwing "Cannot convert type 'System.Web.UI.WebControls.TableCell' to 'System.Web.UI.WebControls.CheckBox' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion" even though the debugger isn't saying this is an error. – Techie Joe Jul 18 '13 at 22:14
1

try using client side script as

$(".btnClass").click(function(){
$(".chkBoxClass").attr("checked", "checked");
});

where btnClass is the class for the button and chkBoxClass is the common class for the checkboxes.

Saksham
  • 9,037
  • 7
  • 45
  • 73
1

The reason you are getting "'System.Web.UI.WebControls.CheckBox' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion" is because you are trying to cast a Cell into a CheckBox.

Please note that I find the CheckBox control inside the Rows Cell's ControlCollection.

Below is tested sample code that works:

Form:

    <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnItemCommand="DetailsView1_ItemCommand">
<AlternatingRowStyle BackColor="White" />
<Fields>
    <asp:ButtonField ButtonType="Button" CommandName="btnSelectAll" Text="Select/Check All Servers" />
    <asp:ButtonField ButtonType="Button" CommandName="btnEdit" Text="Edit" />
    <asp:ButtonField ButtonType="Button" CommandName="btnCancel" Text="Cancel" />
    <asp:ButtonField ButtonType="Button" CommandName="btnSave" Text="Save" />
    <asp:CommandField ButtonType="Button" NewText="CreateRecord" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>

Code Behind:

    DataTable m_table = null;

    public DataTable table
    {
        get
        {
            if (ViewState["m_table"] != null)
                return (DataTable)ViewState["m_table"];
            else
                return null;
        }
        set
        {
            ViewState["m_table"] = value;
        }
    }


    public static T FindControl<T>(ControlCollection controls)
    {
        for (int i = 0; i < controls.Count; i++)
        {
            if (controls[i] is T)
                return (T)(object)controls[i];
        }

            return default(T);
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            table = new DataTable();

            DataColumn col1 = new DataColumn("Field_1");
            DataColumn col11 = new DataColumn("Check_Box_1");
            DataColumn col12 = new DataColumn("Check_Box_2");
            DataColumn col13 = new DataColumn("Check_Box_3");

            col1.DataType = System.Type.GetType("System.String");
            col11.DataType = System.Type.GetType("System.Boolean");
            col12.DataType = System.Type.GetType("System.Boolean");
            col13.DataType = System.Type.GetType("System.Boolean");

            table.Columns.Add(col1);
            table.Columns.Add(col11);
            table.Columns.Add(col12);
            table.Columns.Add(col13);

            DataRow row = table.NewRow();
            row[col1] = "1";
            row[col11] = false;
            row[col12] = false;
            row[col13] = false;

            table.Rows.Add(row);

            DetailsView1.DataSource = table;
            DetailsView1.DataBind();
        }

    }

    protected void DetailsView1_ItemCommand(Object sender, DetailsViewCommandEventArgs e)
    {
        if (e.CommandName == "btnSelectAll")
        {
            foreach (DetailsViewRow row in DetailsView1.Rows)
            {
                for (int i = 0; i < row.Cells.Count; i++)
                {
                    CheckBox cb = FindControl<CheckBox>(row.Cells[i].Controls);
                    if (cb != null)
                    {
                        cb.Checked = true;
                    }                        
                }                    
            }
        }
        if (e.CommandName == "btnSave")
        {
            int j = 0;
            foreach (DetailsViewRow row in DetailsView1.Rows)
            {
                for (int i = 0; i < row.Cells.Count; i++)
                {
                    TextBox tb = FindControl<TextBox>(row.Cells[i].Controls);
                    if (tb != null)
                    {
                        table.Rows[0][j] = tb.Text;
                    }

                    CheckBox cb = FindControl<CheckBox>(row.Cells[i].Controls);
                    if (cb != null)
                    {
                        table.Rows[0][j] = cb.Checked;
                    }
                }
                j++;
            }

            DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
            DetailsView1.DataSource = table;
            DetailsView1.DataBind();
        }
        if (e.CommandName == "btnEdit")
        {
            DetailsView1.ChangeMode(DetailsViewMode.Edit);
            DetailsView1.DataSource = table;
            DetailsView1.DataBind();
        }
        if (e.CommandName == "btnCancel")
        {
            DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
            DetailsView1.DataSource = table;
            DetailsView1.DataBind();
        }
    }
Mausimo
  • 8,018
  • 12
  • 52
  • 70
  • Can you breakdown what's going on in this part of the c# code? `DataRow row = table.NewRow(); row[col1] = "1"; row[col11] = false; row[col12] = false; row[col13] = false;` – Techie Joe Jul 31 '13 at 22:48
  • I am creating a table as the datasource. I define my table above that (The table has 1 string column and 3 boolean checkbox columns). The code you are asking about is creating a TableRow and populating the 4 columns in the example DataTable. Since you are using a database as the datasource you do not need to do this. This is purely for example purposes to show a record in the DetailView. – Mausimo Jul 31 '13 at 22:49
  • The code that you will use is inside the DetailsView1_ItemCommand function. If you take the code I provided, and create a new page with it. It will show a working example. – Mausimo Jul 31 '13 at 22:54
  • I'm modifying the DetailsView11_ItemCommand function but the result when in record edit mode is that the page re-loads and none of the boxes are checked. Is there something I'm missing here? – Techie Joe Jul 31 '13 at 23:07
  • I am not quite sure what "record edit mode is". I thought(based on the above example) that you just have a button that when clicked runs "DetailsView1_ItemCommand". Please take my code markup and codebehind and put it in a fresh page and see if it is doing what you want (it should be). Then debug your other page to determine what is going wrong. Perhaps you are re-load your GridView on every postback and over-writing the changes. If you look at my code, I only bind data to the gridview on the first page load. if (!Page.IsPostBack) – Mausimo Jul 31 '13 at 23:12
  • Sorry, I'll clarify. When I go to enter a new record/entry in the Details view and click the 'Select/Check All Servers' button nothing happens. – Techie Joe Aug 01 '13 at 01:36
  • Do you intend to click the check all button and then the insert button? – Mausimo Aug 01 '13 at 05:37
  • I do not use DetailsView very often. Are you not loading records from the database and then editing them? Or are you creating new records? – Mausimo Aug 01 '13 at 15:37
  • @TechieJoe I updated the code to have a Edit, Save and Cancel button. Since I am using a DataTable instead of a SQL datasource this becomes somewhat convoluted. With a datasource you will use the command field buttons for insert/update etc. – Mausimo Aug 01 '13 at 16:17
  • For this page/DetailsView I am just inserting new records. I have a separate GridView for the editing and viewing of said records. – Techie Joe Aug 01 '13 at 17:07
  • Also, I think the problem is that since you are setting a DataSource for the DetailsView in the form markup, everytime the page post-backs (ie.) button click), the datasource is being re-loaded and changes are destroyed. try programically setting the GridView.DataSource = SqlDataSource1; GridView.DataBind() in your page load and wrap it in if(!Page.IsPostBack){}. If you are just using DetailsView to insert a record. Why not create a stored procedure and a actual form with an insert button. Then just call your stored procedure in your button handler...? – Mausimo Aug 01 '13 at 17:34
  • This is going to take some time and I have to award the bounty now. – Techie Joe Aug 01 '13 at 17:50
  • Would you happen to have a sample to work with before the site forces me to award the bounty? – Techie Joe Aug 01 '13 at 18:14
  • 1
    Sorry, I don't have time right now. I can make an example using a database, later this evening. – Mausimo Aug 01 '13 at 19:11
  • I finally have some dedicated time to go over this again and was looking over your code. I'm in the process of modifying this to a SQL Server connection but the first question I have is do I need to use this save button/code you created instead of using the auto generated code that VS churns out when you place a save button (command field) accordingly? – Techie Joe Oct 07 '13 at 19:59
1

If you set a breakpoint at code like row.Cells[0] and look at the Controls property (either in a Quick Watch window or one of the other debugging windows), you should be able to find your relevant CheckBoxes and figure out how to traverse down to them from each cell.

HOWEVER, this should strike you as a really bad idea. Your code is, right now, tightly coupled to the structure of the page. This is going to be very difficult for you to maintain going forward, and anyone else who works on this project is probably going to spend a very long time trying to figure this out. This code needs to be thrown out.

If you need to have this many fields on a form, consider separating these fields onto a separate page entirely, and actually create the fields separately on the page itself. You may be thinking that this will take more time for users, but honestly -- this form has 13 parameters and 19 CheckBoxes. That is a complicated form that requires some special care and attention.

Finally, the time you (and other developers) save while making improvements to this page and fixing bugs will pay the users back very quickly.

jwheron
  • 2,553
  • 2
  • 30
  • 40
0

Based on Karl Anderson's answer:

protected void DetailsView1_ItemCommand(Object sender, DetailsViewCommandEventArgs e)
{
    if (e.CommandName == "btnSelectAll")
    {
        foreach (DetailsViewRow row in DetailsView1.Rows)
        {
            (row.Cells[1].Controls[0] as CheckBox).Checked = true;
        }
    }

}

Not sure if this fixes everything, but it needs to be pulled into a loop, and I believe Controls[0] will give a handle on the checkbox.

Luke Willis
  • 8,429
  • 4
  • 46
  • 79
  • So I don't need to worry about conversions at all? – Techie Joe Jul 25 '13 at 16:44
  • @TechieJoe I'm not 100% sure this is what you want, but I believe the `TableCell` should have the `CheckBox` inside of it. So, rather than converting the `TableCell`, you need to access its members. The `Controls` array is my best guess after looking at the API. – Luke Willis Jul 25 '13 at 17:19
  • Sounds like `row` is of type `object` which is odd because `Rows` is supposed to be a `DetailsViewRowCollection`. the loop ought to be `foreach (DetailsViewRow row in DetailsView1.Rows)`. That's very odd, though. I thought you could use var in this case. I'll update the answer. – Luke Willis Jul 26 '13 at 14:50
  • I plugged in your code and the page loads with no issues. However, when I click the button to begin a new record entry process, then click the 'select all checkboxes' button the page reloads and the checkboxes remain unchecked. Am I supposed to plugin the exact locations of all 19 checkboxes to the code? I'm a little stumped here. – Techie Joe Jul 29 '13 at 23:05
0

I would try:

protected void DetailsView1_ItemCommand(Object sender, DetailsViewCommandEventArgs e) {
  if (e.CommandName == "btnSelectAll") {
    var controls = new Stack<Control>();
    controls.Push(DetailsView1);
    while (controls.Count > 0) {
      var control = controls.Pop();
      var checkbox = control as CheckBox;
      if (checkbox != null) {
        checkbox.Checked = true;
      }
      foreach (Control childControl in control.Controls) {
        controls.Push(childControl);
      }
    }
  }
}

Recurrent walk trough child controls work even on different control types.

Ondrej Svejdar
  • 21,349
  • 5
  • 54
  • 89
  • I got the code plugged in to my environment but keep getting the following error which I don't have the foggiest clue how to resolve. `Error 1 'System.Web.UI.Control' does not contain a definition for 'Push' and no extension method 'Push' accepting a first argument of type 'System.Web.UI.Control' could be found (are you missing a using directive or an assembly reference?) ` – Techie Joe Jul 29 '13 at 22:55
  • @TechieJoe - have you copied it correctly ? It should be controls.Push(), it seems like you put there a typo - control.Push() – Ondrej Svejdar Jul 30 '13 at 07:24
  • It was indeed a typo there but after that the page loads with no issues. When I go to create a new record, I click the button (in text insert mode) to check all the buttons. The page reloads following the button click and and none of the buttons are clicked. – Techie Joe Jul 30 '13 at 17:07
0

Okay, so all you need to do to access the check box is change this line:

(row.Cells[10] as CheckBox).Checked = true;

to this line:

(row.Cells[10].Controls[0] as CheckBox).Checked = true;

The TableCell holds a collection of controls that are actually used to render the UI. In the case of the CheckBoxField the first control in the collection is the CheckBox.

Now, to make this code a little more scalable, I might do this:

if (e.CommandName == "btnSelectAll")
{
    for (int i = 9; i < 29; i++)
    {
        DetailsViewRow row = DetailsView1.Rows[i];
        (row.Cells[i + 1].Controls[0] as CheckBox).Checked = true; 
    }
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
  • Tried just the scalable code and am still getting boxing/unboxing conversion errors. `Error 1 Cannot convert type 'System.Web.UI.WebControls.TableCell' to 'System.Web.UI.WebControls.CheckBox' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion` – Techie Joe Aug 01 '13 at 17:23
  • @Techie, it looks like I just forgot to copy down the modified line that accesses Controls. I will do that shortly, but you can easily do that yourself in the code. – Mike Perrenoud Aug 01 '13 at 17:30
  • @TechieJoe, please see my edit. As I stated, it was just a copy and paste error in which I forgot to add the access to the `Controls` collection. – Mike Perrenoud Aug 01 '13 at 17:35
  • With the modified code, when I go to create a new record, I click the button (in text insert mode) to check all the buttons. The page reloads following the button click and and none of the buttons are clicked. – Techie Joe Aug 01 '13 at 17:41
  • @TechieJoe, move the code to `OnPreRender`. You'll need to set a flag in the `ItemCommand` handler (e.g. a private class `bool` field) so that you can check it in `OnPreRender`. You'd set it to `true` if `e.CommandName == "btnSelectAll"`. – Mike Perrenoud Aug 01 '13 at 17:51
  • Ok I moved the code to `protected override void OnPreRender(DetailsViewCommandEventArgs e)` and slapped the code in. That errored out so I removed the 'override' part and that produced the same results as my previous post. I don't follow to what you're referring to in the second sentence by setting a flag. – Techie Joe Aug 01 '13 at 18:06
  • I'd sit down and take the time to hammer this out but the site is forcing me to award the bounty pretty quickly. – Techie Joe Aug 01 '13 at 18:17