문제

The error i'm getting is in the title. It has something to do with the array and the for-loop i'm having. I'm trying to store letters from a textbox in a array and then in a session and then search trough those letters in a for-loop and check if the letters in the array is equal to another letter from a txtbox. well....hope some of you know what's wrong. (There is some norwegian letters in there, but don't worry about them) Here is the code from the error:

    Linje 30:     protected void btnSjekkOrd_Click(object sender, EventArgs e)
    Linje 31:     { 
    Linje 32:             for (int i=0; i < arrayOrd.Length; i++ )
    Linje 33:             {
    Linje 34:                 if (txtBokstavSjekk.Text.Length == arrayOrd[i])

Here's all the code:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    //Session
    char [] arrayOrd;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["arrayOrd"] != null)
        {
           arrayOrd = (char[])Session["arrayOrd"];
        }
    }
    protected void Page_Unload(object sender, EventArgs e) 
    {
        Session["arrayOrd"] = arrayOrd;

    }

    protected void btnStart_Click(object sender, EventArgs e)
    {
       char[] arrayOrd = txtOrd.Text.ToCharArray();//Putter txtOrd i array
    }
    protected void btnSjekkOrd_Click(object sender, EventArgs e)
    { 
            for (int i=0; i <= arrayOrd.Length; i++ )
            {
                if (txtBokstavSjekk.Text.Length == arrayOrd[i])
                {
                    labRiktigBokstav.Text += arrayOrd[i];
                }
                else {
                    labFeilBokstaver.Text += "<b>" + arrayOrd[i] + "<b/>";
                }
            }


    }
}
도움이 되었습니까?

해결책

Inside the btnStart_Click you are declaring another copy of the array arrayOrd.
A copy local to the event handler that is no more accessible at the end of the event and then destroyed

Remove the declaration type char[] and your code will reference to the global variable

protected void btnStart_Click(object sender, EventArgs e)
{
   arrayOrd = txtOrd.Text.ToCharArray();//Putter txtOrd i array
}

However, your code is still weak, if the user press the button btnSjekkOrd before the start button the arrayOrd is still null and the error will raise again

protected void btnSjekkOrd_Click(object sender, EventArgs e)
{ 
    if(arrayOrd == null) return; // or message to press the start button

    for (int i=0; i <= arrayOrd.Length; i++ )
    .... 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top