user2376998
user2376998

Reputation: 1071

C# for loop to display all records

I am doing this in wpf c# , I am trying to populate some records from a database. There are 21 records.

Here is how my code looks like:

private void PopulateQuestion(int activityID, int taskID)
{
    IList<ModelSQL.question> lstQuestion = qn.GetRecords(taskID, activityID);

    for( int i= 0 ; i<=lstQuestion.Count()-1; i++)
    {
        TextBlock tb = new TextBlock();
        tb.FontSize = 19;
        tb.FontWeight = FontWeights.Bold;
        tb.Text = lstQuestion[i].QuestionContent;
        tb.TextWrapping = TextWrapping.WrapWithOverflow;
        wrapPanel1.Children.Add(tb);

        TextBox tbox = new TextBox();
        if (lstQuestion[i].Answer.Trim().Length > 0)
        {
            tbox.FontSize = 19;
            tbox.Width = 100;
            tbox.Height = 40;
            tbox.PreviewDrop += new DragEventHandler(tbox_PreviewDrop);
            tbox.Focusable = false; // Disallow user to input anything into it.
            wrapPanel1.Children.Add(tbox);
        }
        answers.Add(lstQuestion[i].Answer);

        if (lstQuestion[i].QuestionNo != lstQuestion[i + 1].QuestionNo)
        {
            StackPanel sp = new StackPanel();
            sp.Width = 1010;
          //  wrapPanel1.Children.Add(sp);
            Label spacing = new Label();
            spacing.Width = 1038;
            spacing.Content = "";
            wrapPanel1.Children.Add(spacing);
        }

    } // end of for each loop.
}

I don't know what is related and what is not, so I just post the part where the for loop lies . the lstQuestion.Count() has 21 counts which is 21 records from database, however I got this error:

{"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"}

So, I suppose something got to do with the for loop where i <=lstQuestion.Count() .

I tried to put i<=lstQuestion.Count()-2 ,

it works but it doesn't display the last 2 records, it displays 19 records instead of 21.

How do I change the for loop such that it displays all 21 records?

I can't use foreach loop because I need to find the next loop value when I am in my current loop.

Upvotes: 1

Views: 317

Answers (1)

Grant Winney
Grant Winney

Reputation: 66489

It's throwing the exception on:

if (lstQuestion[i].QuestionNo != lstQuestion[i + 1].QuestionNo)

When you get to your last (21st) record, it's trying to compare to the 22nd, which doesn't exist.

You need to decide what should happen in the last iteration of your loop. At the very least, something like:

if (i + 1 < lstQuestion.Count())
{
    if (lstQuestion[i].QuestionNo != lstQuestion[i + 1].QuestionNo)
    ...

Upvotes: 7

Related Questions