2015-11-07 92 views
0

由於我仍然是C#的初學者,我在代碼方面存在一些問題。 用戶正在填寫富文本框的一些問題:填充空數據的列表

List<RichTextBox> boxForQuestions = new List<RichTextBox>(); 
for (int i = 0; i < numberOfQuestions; i++) 
{ 
     Label labelForEnumeration = new Label(); 
     labelForEnumeration.Text = (i + 1).ToString(); 
     labelForEnumeration.Text = labelForEnumeration.Text + "."; 
     flowLayoutPanel1.Controls.Add(labelForEnumeration); 

     RichTextBox tempBox = new RichTextBox(); 
     tempBox.Size = new Size(650,60); 
     tempBox.Font = new System.Drawing.Font(FontFamily.GenericSansSerif,11.0F); 
     flowLayoutPanel1.Controls.Add(tempBox); 

     boxForQuestions.Add(tempBox); 
} 

這些問題,我加入到我的字符串列表:

List<string> listOfQuestions = new List<string>(); 
for (int i = 0; i < numberOfQuestions; i++) 
{ 
     listOfQuestions.Add(boxForQuestions[i].Text); 
} 

現在,我想他們隨機在一些在這個功能組:

List<List<string>> questions = new List<List<string>>(); 
static Random rnd = new Random(); 

public void randomizingQuestions() 
{ 
    for (int i = 0; i < numberOfGroups; i++) 
    { 
     List<string> groupOfQuestions = new List<string>(); 
     for (int j = 0; j < numberOfQuestionsPerGroup; j++) 
     { 
       int index = rnd.Next(listOfQuestions.Count - 1); 
       string oneQuestion = listOfQuestions[index]; 

       foreach (string temp in groupOfQuestions) 
       { 
        if (temp != oneQuestion) 
        { 
         groupOfQuestions.Add(oneQuestion); 
        } 
       } 
     } 

     questions.Add(groupOfQuestions); 
    } 
} 

但是,該列表是空的,因爲當我要添加這些問題的PDF文件沒有出來的紙張:

Document document = new Document(iTextSharp.text.PageSize.LETTER, 20, 20, 42, 35); 
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfFile.FileName, FileMode.Create)); 
document.Open(); 

document.Add(new Paragraph("TEST")); 

foreach (List<string> question in questions) 
{ 
     document.NewPage(); 
     foreach (string field in question) 
     { 
       document.Add(new Paragraph(field)); 
     } 
} 

document.Close(); 

你能告訴我我錯了什麼嗎?

+0

你'questions'收到什麼而遍歷?嘗試調試'randomizingQuestions()'方法。我想'groupOfQuestions.Add(oneQuestion);'這行可能沒有執行,因爲每次你輸入第二個'for'循環時,'groupOfQuestions'中就不會有項目,因爲你正在創建它。從你的結尾檢查是否發生了這種情況。 –

回答

0

問題是,groupOfQuestions在循環的開始處是空的,所以沒有字符串在其中進行en化,因此,for-each循環內部的語句從不執行。你也可以使用:

if(!groupOfQuestions.Contains(oneQuestion) 
{ 
    groupOfQuestions.Add(oneQuestion); 
} 

順便說一句,如果命令。新增了執行,你會得到以下異常:

Collection was modified; enumeration operation may not execute. 
+0

我現在看到我的錯誤,但你能解釋我最後一句 – PeMaCN

+0

當然。如果你開始在一個集合上進行迭代(如果你在使用這個枚舉器的時候,添加一個項目到,或者從該集合中刪除一個項目,它會拋出此異常,因爲枚舉數已經過時(不再反映完整集合的項目) –

+0

您有更好的解決方案嗎?你知道嗎?在這個列表中的每個字符串? – PeMaCN