How to sort DataGridView alphabetically when using binding source?

Viewed 144

For some reason dataGridView isn't allowing me to sort it in any way when I'm using a list as a binding source. Any suggestions what to do to get alphabetical sorting working?

    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;
    }
1 Answers

Check source.SupportsSorting, more likely it returns false. To allow sorting look at SortableBindingList.

  • Load your list<Person> into a SortableBindingList e.g. _personList
  • Assign source.DataSource to the SortableBindingList
  • Set the DataGridView.DataSource to source

To obtain a data current Person via the current row in the DataGridView.

Person person = _personList[source.Position];
Related