2016-04-19 74 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