views:

64

answers:

1

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?

A: 

Hope this helps:

DataBinding doesn't occur on Controls until the Controls are created. A TabPage creates child controls only after the TabPage has been made visible. To get DataBinding to occur, you'll need to force the child controls on the TabPage to be created and one way you can do that is by showing/hiding the TabPage (as you have discovered).

Jacob Seleznev
That makes sense. Unfortunately simply calling Show() then Hide() on that TabPage didn't create the Controls like I'd hoped. For now, I'm just forcing the focus to be on that TabPage until I can figure out a better solution.
themarshal