我有一个页面,它使用基于数据库的复选框动态填充列表视图。复选框的文本等于数据库中所有用户的用户名。我正在尝试创建一个控件,其中将删除所选复选框中的用户名。为此,我计划使用一个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>
这是我当前(已损坏)的代码,它当前正在尝试为每个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.
}
对此的任何帮助都将非常感激。
答案 0 :(得分:2)
使用Jimmy在Better way to find control in ASP.NET中给出的漂亮的ControlFinder类,您可以在ListView中递归检索CheckBox并测试它们的ValidationGroup
:
ControlFinder<CheckBox> finder = new ControlFinder<CheckBox>();
finder.FindChildControlsRecursive(lvUsers);
foreach (CheckBox chkBox in finder.FoundControls)
{
if (chkBox.Checked && chkBox.ValidationGroup == "userCheck")
{
// Do something
}
}