2011-05-30 36 views
0

我在列表框中產生了checkboxesat運行時,問題是我怎麼知道選中的複選框是什麼?我如何知道CheckBox被選中?

我嘗試下面的代碼在C#:

CheckBox box; 
if (box.Checked) 
if (box.IsChecked) 

這是下面的代碼:

public partial class Choose_Users 
{ 
    Service1Client C = new Service1Client(); 
    Array a; 
    user_detail d; 
    String F_Name, L_Name; 
    CheckBox user = new CheckBox(); 

    public Choose_Users() 
    { 
     InitializeComponent(); 
     a = C.GetData();    

     for (int i = 0; i < a.Length; i++) 
     { 
      d = (user_detail)a.GetValue(i);     
      user.Name = d.First_name; 
      user.Content= d.First_name; 
      listBox1.Items.Add(user);     
     } 
    } 
    private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     List<user_detail> list = new List<user_detail>(); 
      foreach(CheckBox box in this.listBox1.Items) 
      { 
       if (box.Checked // here my problem is 
       { 

       } 
      } 
     } 
    } 

他們沒有工作。任何幫助?

+0

哪種編程語言? – n00dle 2011-05-30 18:28:42

+1

@Sofia,你發佈了一個問題,它提供了很少的上下文,用於檢查你使用的語言,環境等。請編輯您的問題與相關的細節,並更新標籤,以反映你想要得到答案。 – 2011-05-30 18:29:51

+0

好的,謝謝。它是c# – Sofia 2011-05-30 18:32:10

回答

0

無論編程語言如何,您都需要保留對您動態創建的複選框的引用。

您可以通過的任何本地方法和/或事件之外創建了您的複選框做到這一點:

CheckBox box; 

然後分配本地方法或事件的內部:

box = new CheckBox(); 

然後你可以在代碼和box的任何其他地方訪問 .IsChecked會按你的想法工作。

+0

它沒有工作。我編輯了我的問題併發布了代碼。你會檢查一下嗎? – Sofia 2011-05-30 18:56:45

0

請將Choose_Users中的for循環替換爲以下代碼。以下代碼每次都會創建一個新的複選框對象。

for (int i = 0; i < a.Length; i++) 
{ 
    CheckBox user = new CheckBox(); 
    d = (user_detail)a.GetValue(i); 
    user.Name = d.First_name; 
    user.Content= d.First_name; 
    listBox1.Items.Add(user);     
} 

關於checkstate,box.Checked是完美的。

讓我知道這是否幫助你。

+0

謝謝。我替換了它。但仍然是同樣的問題,特別是我需要知道其他循環中的複選框。 – Sofia 2011-05-31 08:35:05

+0

的foreach(在(c_u.listBox1.Items複選框箱)){ 如果 (box.IsChecked ==真)//這裏的問題 \t \t \t \t { – Sofia 2011-05-31 08:35:47

+0

索非亞,什麼是一個包含。在你的代碼中,A引用了一個單位數組。也許你可以使用斷點調試代碼並查看每個用戶的價值。 – 2011-05-31 09:05:52

0

我們創建的字符串將selectedItem並分配給它檢查boxList的選擇的項目如下:

 
string selectedItem = Box.SelectedItem.Text; 
相關問題