2014-10-22 100 views
0

我有这样的代码,在我读书,我在GridView反序列化的数据,让我们将其命名为FormReadDatabases 它被填充像这样:数据保存在内存

xmlData = (xml.ServiceConfig)serializer.Deserialize(reader); 
dataGridView1.DataSource = xmlData.Databases; 

然后在网格的每一行中我有一个按钮“表”
我点击它一种新的形式出现后FormReadTables

它被填充像这样:

BindingList<xml.Table> table = new BindingList<xml.Table>(); 
dataGridView4.DataSource = table; 

然后我有一个按钮,它可以帮助我添加一个新表,它工作正常,新行出现在FormReadTables,但是当我关闭表单并且我现在在FormReadDatabases,如果我再次单击Table按钮时更改没有保存。

任何想法如何避免这种情况?

+0

'静态'或一些运行时管理器(又名IoC单件)?只是在说'... – 2014-10-22 09:19:59

+0

亲爱的@AndreasNiedermair感谢您的答复,但我是一个初学者,这是什么意思? – Perf 2014-10-22 09:24:44

+0

你使用哪个UI框架? – 2014-10-22 09:29:35

回答

1

这应该是简单的,数据绑定需要使用,可容纳即使形式打开或关闭值的机制发生:

第一种方式可以如下使用静态类型:

static BindingList<xml.Table> table; 

public BindingList<xml.Table> FetchTable() 
{ 
if(table == null) 
{ 
table = new BindingList<xml.Table>(); 
} 
return table 
} 

dataGridView4.DataSource = FetchTable(); 

有一个问题在这里,如果表单能有什么多个实例比可以访问静态变量,然后同时更新表键入需要锁定/同步

另一种选择是表格类型是主窗体的一部分,它加载子窗体并在子窗体的构造函数中获取父窗体的实例,该窗体使用更新并在关闭子窗体后保留。这也将需要同步的多用户/线程访问

public class ParentForm 
{ 
public BindingList<xml.Table> table = new BindingList<xml.Table>(); 
} 

public class ChildForm 
{ 
ParentForm localPf; 
pulic ChildForm(ParentForm pf) 
{ 
localPf = pf; 
} 
dataGridView4.DataSource = localPf.table; 
} 

野老到父窗体对象的表变量的任何变化将持续直到点父窗体是在内存中,但请注意这种实现还不是线程安全的

1

每次窗体打开时,都会创建一个新的BindingList。

BindingList<xml.Table> table = new BindingList<xml.Table>(); 

相反,让其他页面包含一个变量,当你'新'的另一种形式,传入变量。

在打开的窗体上采取的操作是byref,因此将更新您的宿主窗体变量。这意味着下次打开表单时,您传递给它的变量将已经存储以前的更改。根据要求

例子:

我没有我的WinForms手头的环境,但是这显示了重要的概念。

namespace Bob 
{ 
    public class FormLucy 
    { 
     private BindingList<xml.Table> table = new BindingList<xml.Table>(); 

     // your form stuff.. 

     protected void ButtonClick(object sender, EventArgs e) 
     { 
      var frm = new FormTracy(table); 

      // init your forms properties, position etc 

      fmr.ShowDialog(); 
     } 
    } 
} 
+0

这是我需要的,请你给我一个例子代码,因为我是这个新的 – Perf 2014-10-22 09:25:41

+0

但是,如果其他页面不是*静态*,也可以打开和关闭......你是否从最外面的页面注入'table'变量?而且,如果OP使用ASP.NET而不是WinForms? – 2014-10-22 09:28:04

+0

@AndreasNiedermair是的,每一页都可以打开和关闭,所以我需要保存在内存中,我正在用WinForms工作 – Perf 2014-10-22 09:31:44