I have an application that pulls a DataTable using a SQL Select and then loads each item into an ObservableCollection for each class.
ViewModel:
public ObservableCollection<SchachtelEintrag> DataGridMainCollection { get; set; } = new ObservableCollection<SchachtelEintrag>();
private void loadDataGridMainCollection()
{
DataGridMainCollection.Clear();
DataTable dt = new DataTable();
dt = mySql.selectSql("SELECT id, datum, artikel, kurztext, stueckzahl, blechstaerke, rohrmasse, " +
"material, kundenauftrag, ansprechpartner, abteilung, geaendertAm, twoWeeks, prio, ordnerpfad, dateiname FROM auftragstool.orders WHERE zustand = 'zu schachteln' ORDER BY import ASC, blechstaerke DESC");
if (dt.Rows.Count > 0)
{
foreach (DataRow r in dt.Rows)
{
DataGridMainCollection.Add(new SchachtelEintrag
{
Id = Convert.ToInt32(r["id"].ToString()),
Datum = Convert.ToDateTime(r["datum"].ToString()),
Artikel = r["artikel"].ToString(),
Kurztext = r["kurztext"].ToString(),
Stueckzahl = Convert.ToInt32(r["stueckzahl"].ToString()),
Blechstaerke = r["blechstaerke"].ToString(),
Rohrmasse = r["rohrmasse"].ToString(),
Material = r["material"].ToString(),
Kundenauftrag = r["kundenauftrag"].ToString(),
Ansprechpartner = r["ansprechpartner"].ToString(),
Abteilung = r["abteilung"].ToString(),
GeaendertAm = r["geaendertAm"].ToString(),
TwoWeeks = r["twoWeeks"].ToString(),
Prio = r["prio"].ToString(),
Ordnerpfad = r["ordnerpfad"].ToString(),
Dateiname = r["dateiname"].ToString()
});
}
}
}
My DataGrid is bound to the ObservableCollection.
XAML:
<DataGrid ItemsSource="{Binding DataGridMainCollection}"
Selected="{Binding SelectedRow, Mode=TwoWay}">
Now different people are working with the program. As soon as positions are removed or added, the program sends a string to a TCP server. The TCP server sends a command back to the clients, which retriggers the following code:
ViewModel:
loadDataGridMainCollection() //Void from above
Now I am aware that my SelectedItem from the Grid is no longer available to select the item after rebuilding the ObservableCollection.
How does someone else handle this to update an entire collection without losing focus?
Before you clear your collection backup the currently selected item (or just the id of the selectd item). After the clear and refresh you have to find your backup-item in the new filled list.
This can be done with something like: