无法在 Windows 窗体中使用数组

我正在尝试初始化一个数组,将其设置为保存其他变量,然后在用户按下表单上的按钮时使用它。当我尝试使用 button1_Click 类中的数组时,它无法识别它并说它在当前设置中不存在。


namespace WindowsFormsApp1

{

    public partial class Form1 : Form

    {


        string activity;

        int activityTime;

        bool enteredInt = false;


        //initializes variables used to store activities

        string activity1 = "";

        string activity2 = "";

        string activity3 = "";

        string activity4 = "";

        string activity5 = "";



        //intitializes variables used to store activity times

        int activityTime1 = 0;

        int activityTime2 = 0;

        int activityTime3 = 0;

        int activityTime4 = 0;

        int activityTime5 = 0;


        int i;




        public Form1()

        {

            InitializeComponent();


            string[] activities = { activity1, activity2, activity3, activity4, activity5 };

            int[] activityTimes = { activityTime1, activityTime2, activityTime3, activityTime4, activityTime5 };


        }


        private void label1_Click(object sender, EventArgs e)

        {


        }


        private void button1_Click(object sender, EventArgs e)

        {

            enteredInt = Int32.TryParse(textBox2.Text, out activityTime);


            if (textBox1.Text != "" && textBox2.Text != "" && enteredInt == true)

            {

                activity = textBox1.Text;

                activityTime = Int32.Parse(textBox2.Text);

            }

            else

            {

                MessageBox.Show("Please enter valid activity and time.");

            }


            for(i=0;i<5;i++)

            {

                if (activity==activities[i])

                {

                    activity += activities[i];

                    i = 5;

                }

            }




        }


        private void textBox1_TextChanged(object sender, EventArgs e)

        {


        }


        private void textBox2_TextChanged(object sender, EventArgs e)

        {


        }

    }


}

对不起,如果这是一个愚蠢的问题,我真的需要回答。


神不在的星期二
浏览 141回答 1
1回答

FFIVE

你应该定义 int[]activityTimes 作为一个全局变量,把它放在外面public partial class Form1 : Form{&nbsp; &nbsp; string activity;&nbsp; &nbsp; int activityTime;&nbsp; &nbsp; bool enteredInt = false;&nbsp; &nbsp; //initializes variables used to store activities&nbsp; &nbsp; string activity1 = "";&nbsp; &nbsp; string activity2 = "";&nbsp; &nbsp; string activity3 = "";&nbsp; &nbsp; string activity4 = "";&nbsp; &nbsp; string activity5 = "";&nbsp; &nbsp; //intitializes variables used to store activity times&nbsp; &nbsp; int activityTime1 = 0;&nbsp; &nbsp; int activityTime2 = 0;&nbsp; &nbsp; int activityTime3 = 0;&nbsp; &nbsp; int activityTime4 = 0;&nbsp; &nbsp; int activityTime5 = 0;&nbsp; &nbsp; int i;&nbsp; &nbsp; string[] activities=new string[length];&nbsp; &nbsp; public Form1()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; InitializeComponent();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP