1

I have a page which dynamically populates a listview with checkboxes based on a database. The text for the checkboxes is equal to the usernames of all the users in the database. I am trying to create a control in which the usernames in the selected checkboxes will be deleted. To do this, I plan on using a foreach loop that will run for each selected checkbox within the ValidationGroup.

First, here is the ASP .NET code, displaying my approach to formatting the page.

        <asp:ListView ID="lvUsers" runat="server">
            <ItemTemplate>
                    <asp:CheckBox ID="chkUser" runat="server" Text='<%# Eval("UserName") %>' ValidationGroup="userCheck" /><br />
            </ItemTemplate>
        </asp:ListView>

Here is my current (broken) code, which is currently attempting to run a foreach loop for each listview item, when it should only be running a foreach loop for each selected checkbox.

foreach (ListViewItem item in lvUsers.Items) //Trying to replace this with "for each selected checkbox within the userCheck ValidationGroup".
    {

        int UserID = 0;

        String sqlStatement = "SELECT UserID FROM Users WHERE UserName = " + item; //This should be selecting where the UserName = the text value of each selected checkbox.
        SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        SqlCommand comm = new SqlCommand(sqlStatement, conn);
        conn.Open();

        SqlDataReader Reader = comm.ExecuteReader();

        while (Reader.Read())
        {
            UserID = (int)Reader["UserID"];
        }

        Reader.Close();
        conn.Close();

        //Down here I delete all the connected values from various tables based on the value obtained from UserID above.

        }

Any help on this would be much appreciated.

user3530169
  • 369
  • 2
  • 5
  • 14

1 Answers1

2

Using the nice ControlFinder class given by Jimmy in Better way to find control in ASP.NET, you can retrieve the CheckBoxes recursively in the ListView and test their ValidationGroup:

ControlFinder<CheckBox> finder = new ControlFinder<CheckBox>();
finder.FindChildControlsRecursive(lvUsers);

foreach (CheckBox chkBox in finder.FoundControls)
{
    if (chkBox.Checked && chkBox.ValidationGroup == "userCheck")
    {
        // Do something
    }
}
Community
  • 1
  • 1
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
  • 1
    Thank you, that was a brilliant implementation which worked flawlessly! This sounds like it will also be useful for solving my other issue, which was retrieving the text value from the checkboxes. Thank you so much! – user3530169 Apr 20 '16 at 00:37