I’ve been working on a C# project which uses a TabControl. I have a DataTable which is bound, using the same DataView to two different entities, a ListBox in one tab, and a DataGridView in another.
I’ve started saving the user’s selection for those controls between launches. At launch, both the ListBox and the DataGridView are set to the correct values. When the tab switch occurs, if I haven’t changed the selected item in the ListBox, the selected row on the DataGridView gets set to null, and then the SelectedIndexChanged callback for the ListBox gets called, believing that the first item in the list was selected. If, however, I force the tab with the DataGridView to be displayed at launch, the issue does not occur.
Neither control nor the tabs have any callbacks when displayed or entered. I’m running out of ideas here.
Sample Code:
/// <summary>
/// Updates several on-screen controls based on the currently selected item.
/// </summary>
private void updateDisplay()
{
Console.WriteLine("Selection (ListBox): " + myListBox.SelectedIndex);
Console.WriteLine("Selection (DataGridView): " + ((myDataGridView.SelectedRows.Count > 0) ? (""+myDataGridView.SelectedRows[0].Index) : ("null"));
// Update the various labels and textboxes.
}
/// <summary>
/// Callback when the selected index of myListBox changes.
/// </summary>
private void myListBox_SelectedIndexChanged(object sender, EventArgs e)
{
updateDisplay();
}
/// <summary>
/// Callback when the selected row of myDataGridView changes.
/// </summary>
private void myDataGridView_SelectionChanged(object sender, EventArgs e)
{
updateDisplay();
}
Results:
// On launch
Selection (ListBox): 1
Selection (DataGridView): 1
// After tab change
Selection (ListBox): 0
Selection (DataGridView): null
Any ideas?
Hope this helps: