.net数据绑定问题

最近在使用Ado.net Entity Framework和Linq to entities时遇到大量的winform实体数据绑定问题,部分暂时还未能解决,现暂时记录于此,逐步解决。

1.匿名类型不能绑定

现在怀疑匿名类型的属性全部是以字段形式保存在内存中的,而winform空间是不支持字段绑定的,所有的Datamember必须是属性类型。因此,以下代码中被注释的部分在绑定时无法对应到控件的DataPropertyName,而下面的部分则可以。

Here is a technique for binding an arraylist of objects where the objects contain public property that can appear as columns in the datagrid.

有人知道更详细的么?

代码
        //public string AreaCode = string.Empty;
        
//public string AreaName = string.Empty;
        
//public string AreaDesc = string.Empty;
        
//public string TestCode = string.Empty;
        
//public string TestName = string.Empty;
        
//public string TestDesc = string.Empty;

        
public string AreaCode { getset; }
        
public string AreaName { getset; }
        
public string AreaDesc { getset; }
        
public string TestCode { getset; }
        
public string TestName { getset; }
        
public string TestDesc { getset; }

 

 

2. 截断两个数据绑定之间的关联

If you have two controls bound to the same datasource, and you do not want them to share the same position, then you must make sure that the BindingContext member of one control differs from the BindingContext member of the other control. If they have the same BindingContext, they will share the same position in the datasource.

 

代码
private void Form1_Load(object sender, System.EventArgs e)

     
//get a datatable somehow... 
     this.myDataTable = GetATable(); 

     
this.dataGrid1.DataSource = myDataTable; 
 
     
//set a new binding context for the combobox  
     this.comboBox1.BindingContext = new BindingContext();  
     
this.comboBox1.DataSource = myDataTable;  
     
this.comboBox1.DisplayMember = "Col1";  
     
this.comboBox1.ValueMember = "Col1";  

3. CSV文件可以直接以Excel表格的方式直接读取。
4. 绑定到实体是如果不支持双向绑定(two-way binding),应该使用CurrencyManager来刷新。
   
代码
          //use currency manger to sync up the listbox  
          BindingManagerBase bm 
= this.listBox1.BindingContext[myArrayList];  
          CurrencyManager cm 
= (CurrencyManager) bm;  
          
if (cm != null)  
               cm.Refresh();                 
 
          
//Or, you can just reset the datasource 
          
//listBox1.DataSource = null;  
          
//listBox1.DataSource = myArrayList;  

 


 

 

可以参照这篇文档,提到了两个数据绑定的问题。

  绿森林  http://www.cnblogs.com/greeny/archive/2010/01/26/1656431.html

1. LINQ的查询结果无法直接作为DataGridView的数据源

2. 字符串无法直接作为DataGridView的数据源


 

posted @ 2010-05-21 09:42  laughter  阅读(378)  评论(1编辑  收藏  举报