通过下一个和上一个按钮解析的文本框值数组

时间:2016-02-02 21:40:59

标签: c# arrays winforms textbox

我在winform中获得了一个带有下一个上一个按钮的表单。我有一系列数字存储在一个数组中,并想通过按钮浏览它们。我需要帮助我如何做到这一点&一个可能的例子。我已经尝试过并且到处寻找,但是因为我现在碰到了一堵砖墙而无法得出结论。

private nextButton_Clicked()
{
    int counter;

    if (counter == 0)
    {
        //content of first page
    } 
}

以上仅适用于第二页,但我需要功能性和非重复性。

2 个答案:

答案 0 :(得分:0)

private void btnNext_Click(object sender, EventArgs e)
{

    if (pos < someArray.Count() - 1)
    {
        pos++;
        label1.Text = someArray[pos];
    }
}

private void btnPrev_Click(object sender, EventArgs e)
{

    if (pos > 0)
    {
        pos--;
        label1.Text = someArray[pos];
    }
}

`

答案 1 :(得分:0)

如果您正在寻找一种可重用的处理方法,我会将分页逻辑分解为一个单独的类。解释是内联的。 非常重要要注意,此实现假定您正在分页的数据可以安全地多次枚举。因为它听起来像你正在使用的数据结构是一个数组,这应该没问题。

aababcabcd

以下是一些使用MSTest的测试,显示了它的工作原理:

public class Pageable<T>
{
    //This is your array data
    private readonly IEnumerable<T> _data;

    //Number of items per page
    private readonly int _pageSize;

    //The current page (1-indexed)
    private int _currentPage;

    //Calculate Total number of pages based on number of items and user defined page size
    public int TotalPages
    {
        get { return (int)Math.Ceiling((double)_data.Count() / _pageSize); }
    }

    //Constructor to load the data
    public Pageable(IEnumerable<T> data, int pageSize = 10)
    {
        _currentPage = 1;
        _pageSize = pageSize;
        _data = data;
    }

    public IEnumerable<T> NextPage()
    {
        //increment the page
        _currentPage++;

        //make sure that the incremented value does not exceed total pages
        if (_currentPage >= TotalPages) _currentPage = TotalPages;

        return GetPage(_currentPage);
    }

    public IEnumerable<T> PreviousPage()
    {
        //decrement  the page
        _currentPage--;

        //make sure the decremented value is not less than 0
        if (_currentPage <= 0) _currentPage = 0;

        return GetPage(_currentPage);
    }

    public IEnumerable<T> GetCurrentPage()
    {
        return GetPage(_currentPage);
    }

    public IEnumerable<T> GoToPage(int page)
    {
        if (page <= 0)
            throw new Exception("Cannot be less than 1.");
        if (page > TotalPages)
            throw new Exception("Cannot be greater than total number of pages.");

        _currentPage = page;

        return GetPage(_currentPage);
    }

    //The page value is the value that the user would expect.  (1-indexed)
    private IEnumerable<T> GetPage(int page)
    {
        //Correct for 1-indexed page value;
        var pageIndex = page - 1;

        //Use Language Integrated Query (LINQ) to calculate the items we need
        //Skip the first Nth items (pageIndex * _pageSize))
        //Take the next _pageSize items
        return _data.Skip(pageIndex * _pageSize).Take(_pageSize);
    }
}