【问题标题】:Change Repeater Index at runtime在运行时更改中继器索引
【发布时间】:2017-09-29 15:19:58
【问题描述】:

我有一个填充了 4 个值的中继器控件。

1 类_1
2 类_2
3 类_4
4 类_3

Repeater 绑定在索引值上,因此当显示Repeater 时,它会将数据显示为:
Class_1
Class_2
Class_4
Class_3。

但我想将数据显示为:

Class_1
Class_2
Class_3
Class_4。

我需要在绑定时更改顺序。 在绑定或显示数据时,我需要先显示索引 4 的值,然后再显示索引 3。

【问题讨论】:

  • 对源数据进行排序,然后绑定到Repeater。 index 上的绑定与它无关。
  • 我认为你必须实现你的 IEnumerable 类并按照你的意愿编写它的枚举器
  • @VDWWD 排序可以按顺序进行。在我的情况下,我需要将索引值显示为:1、2、4、3 而不是 1、2、3、4
  • @S.Petrosov 你能提供一些例子吗?
  • 你可以随意排序。如果您希望它为 1,2,4,3,您可以在将其绑定到中继器之前对其进行排序。

标签: c# asp.net .net vb.net asprepeater


【解决方案1】:

以上是IEnumerable 类实现的示例,它将按 1、2、4、3 的顺序提供值:

public class MyEnumerable<T> : IEnumerable<T>
{
    private List<T> _list;

    public MyEnumerable()
    {
        _list = new List<T>();
    }

    public void Add(T value)
    {
        _list.Add(value);
    }

    public bool Remove(T value)
    {
        return _list.Remove(value);
    }

    public bool Exists(Predicate<T> value)
    {
        return _list.Exists(value);
    }

    public bool Contains(T value)
    {
        return _list.Contains(value);
    }
    public IEnumerator<T> GetEnumerator()
    {
        for (int i = 0; i < _list.Count; i++)
        {
            if (i == 2)
            {
                i++;
                yield return _list[i];
                yield return _list[i-1];
            }
            else
            {
                yield return _list[i];
            }
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        for (int i = 0; i < _list.Count; i++)
        {
            if (i == 3)
            {
                yield return _list[i + 1];
                yield return _list[i];
                i += 2;
            }
            else
            {
                yield return _list[i];
                i++;
            }
        }
    }
}

但如果您的清单超过 4 项,您需要根据需要更改 GetEnumerator()

这是一个示例,它将打印“First”、“Second”、“Third”、“Fourth”,而在列表中它们将按“First”、“Second”、“Fourth”、“Third”的顺序排列。

static void Main(string[] args)
{
    MyEnumerable<string> myEnumerable = new MyEnumerable<string>()
    {
        "First","Second","Fourth","Third"
    };
    foreach (var tmp in myEnumerable)
    {
        Console.WriteLine(tmp);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多