切换选项卡重置数据绑定选择 [英] Switching tab resets databound selection

查看:128
本文介绍了切换选项卡重置数据绑定选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用一个使用 TabControl 的C#项目。我有一个 DataTable 被绑定,使用相同的 DataView 到两个不同的实体,一个 ListBox 在一个选项卡,另一个 DataGridView

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.

我已经开始在启动之间保存用户对这些控件的选择。在启动时, ListBox DataGridView 都设置为正确的值。当选项卡切换发生时,如果我没有更改 ListBox 中的选定项目,则 DataGridView 设置为 null ,然后 ListBox SelectedIndexChanged 回调$ c>被调用,相信列表中的第一个项被选中。但是,如果在启动时强制使用 DataGridView 的标签,则不会出现此问题。

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.

示例代码:

/// <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();
}

结果:

//启动时

选择(ListBox):1

选择(DataGridView):1

Results:
// On launch
Selection (ListBox): 1
Selection (DataGridView): 1

//选项卡更改后

选择(ListBox):0

选择(DataGridView):null

// After tab change
Selection (ListBox): 0
Selection (DataGridView): null

任何想法?

推荐答案

希望这个有助于:


DataBinding不会发生在控件
上,直到创建控件。 A
TabPage创建子控件只有
在TabPage成为
可见后。要获取DataBinding发生,
您需要强制孩子
控件在TabPage上创建
,一种方式可以通过
显示/隐藏TabPage(如您所发现的
)。

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).

这篇关于切换选项卡重置数据绑定选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆