无法在tabControl1_Selected事件的winform中绑定列表框?

时间:2015-10-15 11:17:43

标签: c# winforms listbox

MainForm.cs

 public MainForm() 
 {
     InitializeComponent();
     tabControl1.Selected += new TabControlEventHandler(tabControl1_Selected);
 }

 private void tabControl1_Selected(object sender, TabControlEventArgs e)
 {
     //bind listbox
     MyUserControl obj = new MyUserControl();
     obj.LoadListBox();
     obj.Refresh();
 }

在MyUserControl.cs里面

 public void LoadListBox()
 {
     listBox1.Items.AddRange(JsonConvert.DeserializeObject <object[]> (File.ReadAllText("MyData.json")));
 }

为什么不刷新或绑定?在调试模式下,它显示数据但未在UI表单上显示任何线索?

1 个答案:

答案 0 :(得分:1)

您应该将用户控件实例添加到winform。

 private void tabControl1_Selected(object sender, TabControlEventArgs e)
 {
     //bind listbox
     MyUserControl obj = new MyUserControl();
     obj.LoadListBox();
     obj.Refresh();
     this.Controls.Add(obj); //Add control instance to the winform.
 }

我建议,在表单中添加Panel控件,并将用户控件添加到此面板。在添加用户控件之前,您需要清除面板。但这取决于你的要求。也许你不需要每次都添加控件。所以你应该相应地编写你的代码。

 private void tabControl1_Selected(object sender, TabControlEventArgs e)
 {
     //I guess you have a Panel control named as pnl.
     pnl.Controls.Clear(); //Clear all child control from panel.
     MyUserControl obj = new MyUserControl();
     obj.LoadListBox();
     obj.Refresh();
     pnl.Controls.Add(obj); //Add control instance to the panel.
 }