2016-04-19 49 views
1

我有一个页面,动态地填充一个基于数据库的复选框的列表视图。复选框的文本等于数据库中所有用户的用户名。我正在尝试创建一个控件,其中所选复选框的用户名将被删除。为此,我计划使用一个将在ValidationGroup中为每个选中的复选框运行的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循环运行的每个ListView项,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. 

     } 

对此的任何帮助将不胜感激。

回答

2

使用Better way to find control in ASP.NET吉米给出的不错ControlFinder类,你可以在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 
    } 
} 
+1

谢谢你,这是一个辉煌的实现其完美无缺!这听起来像对于解决我的其他问题也是有用的,这个问题是从复选框中检索文本值。非常感谢! – user3530169