从ValidationGroup检索选定的复选框值

本文关键字:复选框 ValidationGroup 检索 | 更新日期: 2024-10-18 19:22:35

我有一个页面,它根据数据库动态地用复选框填充列表视图。复选框的文本等于数据库中所有用户的用户名。我正在尝试创建一个控件,其中所选复选框中的用户名将被删除。为此,我计划使用foreach循环,该循环将针对ValidationGroup中的每个选定复选框运行。

首先,这里是ASP.NET代码,显示了我格式化页面的方法。

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

这是我当前的(坏掉的)代码,它当前正试图为每个列表视图项运行foreach循环,而它应该只为每个选中的复选框运行foreach环。

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.
        }

如有任何帮助,我们将不胜感激。

从ValidationGroup检索选定的复选框值

使用Jimmy以Better方式提供的漂亮的ControlFinder类在ASP.NET中查找控件,您可以在ListView中递归检索复选框,并测试它们的ValidationGroup:

ControlFinder<CheckBox> finder = new ControlFinder<CheckBox>();
finder.FindChildControlsRecursive(lvUsers);
foreach (CheckBox chkBox in finder.FoundControls)
{
    if (chkBox.Checked && chkBox.ValidationGroup == "userCheck")
    {
        // Do something
    }
}