试图使其成为当我单击Windows窗体按钮时,将显示文本文件中的数字

时间:2012-11-28 11:48:39

标签: c# winforms

以下是下面的代码,我确定有一种简单的方法可以做到这一点,但我是新手并努力奋斗。如何让textBoxLatitude.Text显示items [0]?

namespace GPSCalculator
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                List<float> inputList = new List<float>();
                TextReader tr = new StreamReader("c:/users/tom/documents/visual studio 2010/Projects/DistanceCalculator3/DistanceCalculator3/TextFile1.txt");
                String input = Convert.ToString(tr.ReadToEnd());
                String[] items = input.Split(',');

            }



            private void buttonNext_Click(object sender, EventArgs e)
            {

                textBoxLatitude.Text = (items[0]);

            }
        }
    }

3 个答案:

答案 0 :(得分:1)

项目当前是局部变量..需要使其成为类变量

答案 1 :(得分:0)

将items数组移动到class field。

public partial class Form1 : Form
{
    private String[] items; // now items available for all class members

    public Form1()
    {
        InitializeComponent();
        List<float> inputList = new List<float>();
        TextReader tr = new StreamReader(path_to_file);
        String input = Convert.ToString(tr.ReadToEnd());
        items = input.Split(',');
    }

    private void buttonNext_Click(object sender, EventArgs e)
    {
        textBoxLatitude.Text = items[0];
    }
}

另外我相信你想在每个按钮点击上显示下一个项目。然后你还需要项目索引的字段。

public partial class Form1 : Form
{
    private String[] items; // now items available for all class members
    private int currentIndex = 0;

    public Form1()
    {
        InitializeComponent();
        // use using statement to close file automatically
        // ReadToEnd() returns string, so you can use it without conversion
        using(TextReader tr = new StreamReader(path_to_file))
              items = tr.ReadToEnd().Split(',');    
    }

    private void buttonNext_Click(object sender, EventArgs e)
    {
        if (currentIndex < items.Length - 1)
        {
            textBoxLatitude.Text = items[currentIndex];
            currentIndex++
        }
    }
}

答案 2 :(得分:0)

将数组移到函数外部。这将使整个班级都可以使用。

namespace GPSCalculator
{
    public partial class Form1 : Form
    {
        String[] items;

        public Form1()
        {
            InitializeComponent();
            List<float> inputList = new List<float>();
            TextReader tr = new StreamReader("c:/users/tom/documents/visual studio 2010/Projects/DistanceCalculator3/DistanceCalculator3/TextFile1.txt");
            String input = Convert.ToString(tr.ReadToEnd());
            items = input.Split(',');
        }



        private void buttonNext_Click(object sender, EventArgs e)
        {

            textBoxLatitude.Text = (items[0]);

        }
    }
}