0

这是下面的代码,我确定有一种简单的方法可以做到这一点,但我对此并不陌生并且正在苦苦挣扎。如何让 textBoxLatitude.Text 显示项目 [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]);

            }
        }
    }
4

3 回答 3

1

items 当前是一个局部变量..需要使它成为一个类变量

于 2012-11-28T11:51:42.383 回答
0

将项目数组移动到类字段。

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++
        }
    }
}
于 2012-11-28T11:51:29.790 回答
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]);

        }
    }
}
于 2012-11-28T11:52:37.503 回答