2015-11-07 89 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