locked
Proper way to store state of gridview checkboxes in database and retrieving them later by individual db records RRS feed

  • Question

  • User-718146471 posted

    Hello folks, I have been struggling a bit trying to figure out how to store the state of the grid views and other items on my asp.net web form. What I would like to do is save the state of the multi-item asp.net controls and then when clicking on the record in a grid view, display the record with the options selected. So, for the sake of argument, I have two data lists and a grid view. What do I need to do on the front and back to insert that data into the DB and then using a viewing form retrieve the selections? Here is the related section of web form code I'm speaking of.

                        <asp:Panel ID="pnlDevDisplay" runat="server" Visible="true">
                            <div style="width: 100%; text-align: center;">
                                <asp:Label runat="server" Text="Contacts" Font-Bold="True"></asp:Label>
                            </div>
                            <div style="width: 100%; height: 150px; overflow: scroll">
                                <asp:DataList ID="dlDevs" runat="server" Width="664px">
                                    <AlternatingItemStyle BackColor="#CCDDFF" Wrap="False" />
                                    <ItemStyle Wrap="False" HorizontalAlign="Left" VerticalAlign="Top" />
                                    <ItemTemplate>
                                        <table width="95%">
                                            <tr align="left" valign="top">
                                                <td style="width: 15%; align-items: center;">
                                                    <asp:HiddenField ID="hdnChkRow" runat="server" />
                                                    <asp:CheckBox ID="chkRow" runat="server" value='<%# Eval("Username") %>' />
                                                </td>
                                                <td style="width: 50%; text-align: left;">
                                                    <asp:Label ID="lblName" runat="server" Text='<%# Eval("ADName") %>' /></td>
                                                <td style="width: 35%; text-align: left;">
                                                    <asp:Label ID="lblUsername" runat="server" Text='<%# Eval("Username") %>' /></td>
                                            </tr>
                                        </table>
                                    </ItemTemplate>
                                    <HeaderTemplate>
                                        <table width="95%">
                                            <tr>
                                                <th></th>
                                                <th>Name</th>
                                                <th>PIN</th>
                                            </tr>
                                        </table>
                                    </HeaderTemplate>
                                </asp:DataList>
                            </div>
                            <div>
                                <asp:Label ID="lblSelDevs" runat="server"></asp:Label>
                            </div>
                        </asp:Panel>
                    </div>
                </div>
                <div id="tabs-3">
                    <div>
                        <div style="width: 100%; text-align: center;">
                            <asp:Label runat="server" Text="Programming Languages" Font-Bold="True"></asp:Label>
                        </div>
                        <table>
                            <tr>
                                <td>
                                    <asp:DataList ID="dlLanguages" runat="server" 
    RepeatDirection="Horizontal" RepeatColumns="6" Width="669px" ToolTip="Languages"
     
    TabIndex="26">
    
                                        <ItemTemplate>
                                            <div style="text-align: left;">
                                                <asp:HiddenField ID="hfSelected" runat="server" />
                                                <asp:CheckBox ID="cbLang" AutoPostBack="true" 
    runat="server" value='<%# Eval("Value") %
    >' />&nbsp;&nbsp;<asp:Label ID="lblLang" runat="server" 
    ToolTip='<%# Eval("Name") %>' Text='<%# Eval("Name") %>' />
    
                                            </div>
                                        </ItemTemplate>
                                    </asp:DataList>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div id="tabs-4">
                    <div>
                        <div style="width: 100%; text-align: center;">
                            <asp:Label runat="server" Text="Environment" Font-Bold="True" ToolTip="Environment"></asp:Label>
                        </div>
                        <asp:GridView ID="gvBuildMachine" Width="100%" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvBuildTools_RowDataBound">
                            <AlternatingRowStyle BackColor="#CCDDFF" />
                            <Columns>
                                <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                                    <ItemTemplate>
                                        <asp:HiddenField ID="hdnChecked" runat="server" Value='<%# 
    Bind("Value") %>' />
                                        <asp:CheckBox ID="CheckBox" runat="server" Style="text-align:
     center" TextAlign="Left" />
                                    </ItemTemplate>
                                    <ItemStyle HorizontalAlign="Center" />
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Operating System">
                                    <ItemTemplate>
                                        <asp:Label ID="Label25" runat="server" Text='<%# Bind
    ("Name") %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Version">
                                    <ItemTemplate>
                                        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                            <RowStyle HorizontalAlign="Center" VerticalAlign="Top" />
                        </asp:GridView>
                    </div>
                </div>
    

    I know this can be done, I think I have just forgotten how in the past. Any help appreciated!!!

    Thursday, December 21, 2017 3:58 PM

Answers

  • User475983607 posted

    Ok, I think I am closer to what I'm trying to do. I have it step through the value I am attempting to match and it finds it, however the row remains unchecked. I am sure it has to be something simple. Here's the code

    I don't understand the issue.  Are you saying isChk is set to true but this state is not reflected in the resulting HTML?  If so, that kind of error is commonly due to the order of events where a later event overwrite the state of a previous event.

    I suggest rethinking of the design.  Move the logic to SQL using a table JOIN rather than writing a join in a C# loop and within a Web Forms event. 

    If you are married to this design for some reason, then post enough code to reproduce the issue.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 2, 2018 4:53 PM

All replies

  • User-707554951 posted

    Hi bbcompent1,

    From my understanding, you want to display the options you selected in another page.

    So, you need to save the option in somewhere.

    If that the case, you could save it in session variable( back end) or save in localstorage

    https://stackoverflow.com/a/11609448

    http://www.c-sharpcorner.com/UploadFile/b926a6/textbox-data-transfer-one-page-to-another-page-using-various/

    If not, would you please provide us with detailed description about what you want to do.

    Best regards 

    Cathy

    Friday, December 22, 2017 7:17 AM
  • User-718146471 posted

    I can see that being used for saving the session in case the browser goes to heck. But what I'm trying to do is save the checked items in the grid views, list views, etc into the database because the viewing is going to be done from a completely different PC. That's why I need to store the checked items in the database. Writing/Reading the info from the database I know how to do. What I need to know is how to store the selection options and write them to the database table and retrieve those checked items later when the same record is viewed. Certain users will have the ability to create requests, while others can create/view/manage them. I have a Grid View and a couple Data List controls.

    Friday, December 22, 2017 11:15 AM
  • User-718146471 posted

    Ok, I'm trying to work my way through this issue. I think a way to store the checked items is to toss them into a stringbuilder and pass that into the database. However, I am running into a problem where it complains that Object reference not set to an object when I check the status of the checkbox. Here's the code:

                StringBuilder sbDevs = new StringBuilder();
                {
                    CheckBox cb = (CheckBox)gvDevs.FindControl("chkSelPin");
                    Label lb = (Label)gvDevs.FindControl("lbUsername");
                    foreach (GridViewRow row in gvDevs.Rows)
                    {
                        if (cb.Checked) // this is where it drops to the catch
                        {
                            sbDevs.Append(lb.Text.ToString() + ",");
                        }
                    }
    
    Friday, December 22, 2017 12:43 PM
  • User-718146471 posted

    Ok, got that problem fixed. This is what I'm doing now and it is iterating the gridview:

                    foreach (GridViewRow row in gvDevs.Rows)
                    {
                        if (((CheckBox)row.FindControl("chk")).Checked)
                        {
                            Label lb = (Label)row.FindControl("lblUsername");
                            sbDevs.Append(lb.Text.ToString() + ",");
                        }
                    }
    
    Friday, December 22, 2017 1:35 PM
  • User-718146471 posted

    Ok, running into a problem trying to capture the value of a label text but I get this error:

    System.InvalidCastException: Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.Web.UI.WebControls.Label'.

    This is how I'm trying to code out the C#:

    OSVers += (((Label)row.FindControl("TextBox4")).Text.ToString()) + " ,";

    How do I capture the label's text value row by row?

    Friday, December 22, 2017 2:02 PM
  • User475983607 posted

    You're trying to cast a TextBox to a label.  I assume you need to change the cast to a TextBox like this...

    OSVers += (((TextBox)row.FindControl("TextBox4")).Text.ToString()) + " ,";

    Friday, December 22, 2017 2:42 PM
  • User-718146471 posted

    Thanks for that, it worked well! Now my question is, how do I pull these values out and mark them in the corresponding grid views and data lists? I get that I will probably have to pull them in from the database as a list, but how do I walk through the grid view/data list and mark the rows that match? Do I do a search by string? Because that is what I will be storing in the DB. Any ideas how to do that?

    Friday, December 22, 2017 4:27 PM
  • User475983607 posted

    I don't understand the problem you are trying to solve.  I think you need to build a DB schema to support an application feature that you're building.  

    Can you explain what you are trying to do at a high level?

    Friday, December 22, 2017 5:03 PM
  • User-718146471 posted

    Ok, at a high level, I am storing the values of the labels in each row if those particular rows are checked. When I read the values stored (comma delimited) I would like to have those options checked like they were before updating the database. So the reviewer of the request sees all options as selected.

    So if I choose Operating Systems: Windows Server 2008 R2, Windows Server 2012 R2 in my grid, I would like those options to be checked when reading the record.

    Friday, December 22, 2017 5:21 PM
  • User475983607 posted

    Ok, at a high level, I am storing the values of the labels in each row if those particular rows are checked. When I read the values stored (comma delimited) I would like to have those options checked like they were before updating the database. So the reviewer of the request sees all options as selected.

    So if I choose Operating Systems: Windows Server 2008 R2, Windows Server 2012 R2 in my grid, I would like those options to be checked when reading the record.

    I would use a data driven approach.  Create a lookup table of all the options. Use this table to create the checkboxes.  Add another table that joins the options to the this process or user or this business operation.  From there it's a simply query to get the selected options.  If the user has the option (the joins exists) then the user selected the option.

    There is nothing stopping you from building a delimited string which is the same idea as above.  The difference being the the join is invoked outside the DB in a looping construct.  The CSV approach requires that you split the CSV string into an array of strings and write code to loop through all the possible options that match the split CSV string.  If the options are hardcoded in the markup then you can write the loop in JavaScript.  If the options are hardcoded in a server control then write the logic in the code behind.

    Sunday, December 24, 2017 12:19 PM
  • User1120430333 posted

    You could have used a DTO, XML serialize the DTO and saved it as string data to a DB table record. You can then retrieve the XML string data from the DB table record and deserialize it back to the DTO.

    https://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp

    Tuesday, December 26, 2017 8:48 AM
  • User-718146471 posted

    Create a lookup table of all the options. Use this table to create the checkboxes.  Add another table that joins the options to the this process or user or this business operation.  From there it's a simply query to get the selected options.  If the user has the option (the joins exists) then the user selected the option.

    Ok, that sounds logical. Do you have an example of how I might do this? The selections are saved as a comma separated string in the DB. So, here is what the language selection would look like from the DB.

    ASP.NET, C#, VB.NET, AJAX

    For speed, I am using a mock which creates the options for the Grid View that has these options there.

    Friday, December 29, 2017 1:53 PM
  • User-718146471 posted

    Ok, I think I am closer to what I'm trying to do. I have it step through the value I am attempting to match and it finds it, however the row remains unchecked. I am sure it has to be something simple. Here's the code:

                List<string> seldev = new List<string>();
                string dev = hfSelectedDevs.Value;
                seldev = dev.Split(',').ToList<string>();
                foreach (GridViewRow row in gvDevs.Rows)
                {
                    Label lblSAM = (row.FindControl("lblsaMAccountName") as Label);
                    CheckBox isChk = (row.FindControl("chk") as CheckBox);
                    for (int i = 0; i < seldev.Count; i++)
                    {
                        if (seldev[i].ToString() == lblSAM.Text.ToString())
                        {
                            isChk.Checked = true;
                        }
                    }
                }
    
    Tuesday, January 2, 2018 4:24 PM
  • User475983607 posted

    Ok, I think I am closer to what I'm trying to do. I have it step through the value I am attempting to match and it finds it, however the row remains unchecked. I am sure it has to be something simple. Here's the code

    I don't understand the issue.  Are you saying isChk is set to true but this state is not reflected in the resulting HTML?  If so, that kind of error is commonly due to the order of events where a later event overwrite the state of a previous event.

    I suggest rethinking of the design.  Move the logic to SQL using a table JOIN rather than writing a join in a C# loop and within a Web Forms event. 

    If you are married to this design for some reason, then post enough code to reproduce the issue.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 2, 2018 4:53 PM