【问题标题】:How to sort DataGridView alphabetically when using binding source?使用绑定源时如何按字母顺序对 DataGridView 进行排序?
【发布时间】:2022-01-23 19:02:34
【问题描述】:

由于某种原因,当我使用列表作为绑定源时,dataGridView 不允许我以任何方式对其进行排序。有什么建议可以让字母排序正常工作吗?

    public partial class Form : Form
{
    List<Person> people = new List<Person>();
    string personsfile = "c:\\temp1\\people.json";
    public Form()
    {
        InitializeComponent();

        henkilot = DeserializeJSON();
        if (people== null)
        {
            people= new List<Person>();
        }
        populateDataGrid();
    }

    public void SerializeJSON(List<Person> input)
    {
        string json = JsonConvert.SerializeObject(input);
        //write string to file
        System.IO.File.WriteAllText(personsfile, json);
    }
    public List<Person> DeserializeJSON()
    {
        if (File.Exists(personsfile))
        {
            using (StreamReader r = new StreamReader(personsfile))
            {
                string json = r.ReadToEnd();
                return JsonConvert.DeserializeObject<List<Person>>(json);
            }
        }
        else
            return null;
    }

    public void populateDataGrid()
    {
        BindingSource source = new BindingSource();
        source.DataSource = people;
        dataGrid.DataSource = source;
    }

【问题讨论】:

标签: c# visual-studio winforms


【解决方案1】:

检查 source.SupportsSorting,它更有可能返回 false。要允许排序,请查看SortableBindingList

  • 将您的列表 加载到 SortableBindingList 例如_personList
  • source.DataSource 分配给SortableBindingList
  • 将 DataGridView.DataSource 设置为 source

通过DataGridView中的当前行获取数据当前Person。

Person person = _personList[source.Position];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-29
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多