Use DataBinding to maintain the alphabetic short between listBoxes

What must I write to bind the indexes of them?

I recommended a datagridview; you seem to have tabular data that you want to show in a tabular fashion.. However, we'll demo all of it.

Easiest route:

  • Make a new winforms project
  • Add a DataSet type of file, open it, right click the design surface and choose Add .. DataTable
  • Name the table Client
  • Right click it and add column, call it DNI, use the props grid to make its type Int32
  • Add a string column Name
  • Add an int column Telephone
  • Save, switch to Form1 designer
  • Open Data Sources window (View menu, Other Windows)
  • Drag the Client node onto the form. A datagridview appears along with some stuff in the tray. Remove the navigator; it's not so useful in this context
  • Add 3 listboxes to the form
  • For each listbox:
    • Use the props grid to set its DataSource to the bindingsource
    • Set the DisplayMember to a different column - one DNI, the other Name and the third Telephone

That's it for now, run the app. Type some data in the datagridview. Note that when you sort by clicking the DGV header, the listboxes follow; this is because the sort instruction is being carried out by the bindingsource, and all controls bind through the bindingsource:

enter image description here

So that's thngs bound through a bindingsource to a strongly typed datatable, which is conceptually not really any different to what you have. The bit of work making the table and its columns in the design surface is the notional equivalent of making a class with properties. Indeed if you were to open the DataSetBlahBlah.Designer.cs file you'd find a class ClientRow with 3 properties DNI, Name, Telephone

You could change up everything you've made to be based on e.g. a List<Client> but your sorting life becomes slightly more awkward because a BindingSource doesn't understand how to sort it. As such you'd end up with something like:

//class property
private List<Client> Clients = new();

//in constructor
clientBindingSource.DataSource = Clients;

//in button that does sorting:
clientBindingSource.DataSource = Clients.OrderBy(c => c.name); //etc

Personally I'd leave it as a strongly typed datatable; for what you'd want out of a List<Client> a ClientDataTable collection of ClientRow are surface similar enough..

Clients.Where(c => c.Name == "John"); //how you might search a List<client>
ClientsDT.Where(c => c.Name == "John"); //how you might search a ClientDataTable

Clients.Add(new Client(){ DNI = 1, Name = "a", Telephone = 1 } ); //add to a List<Client>
ClientsDT.AddClientsRow(1, "a", 1); //how you might add to a ClientDataTable

etc