Skip to main content

BindingSource

在编写一个小工具的时候需要将一个自定义的集合绑定到DataGridView。DataGridView是.net 2.0中新的一个网格控件。DataGridView的功能非常的强大,我在使用中确遇到一个小小的问题。
我自定的集合如下:
public class CustomClassCollection : System.Collections.Generic.List<CustomClass>
{
}

CustomClass本身是有两个String类型的属性(Propertie)。我在WinForm的构造函数里面:

CustomClassCollection ccl = new CustomClassCollection();
dataGridView.DataSource = ccl;

虽然还没有数据,但是在DataGridView里面已经显出2个Title,即CustomClass的那2个属性,然后却遇到的个问题:我通过一个button Click事件向ccl里添加了东西,却没有找到DataGrid里面的DataBind()事件,而且dataGridView并没有自动的更新。DataGridView的Refresh()似乎和更新数据也没有关系。
在网上查找资料,找到BindingSource这个类。只需要,先将cll Bind到BindingSource上,再将BindingSource作为数据源Bind到DataGridView。向cll添加数据以后调用BindingSource的ResetBindings()就可以更新DataGridView:
先声明一个BindingSource:

BindingSource bs = new BindingSource();

再调用:

bs.DataSource = ccl;
dataGridView.DataSource = bs;

在添加数据的方法的最后调用:

bs.ResetBindings(false);


Key Word: DataGridView BindingSource 数据同步 更新

Comments

Anonymous said…
thankx a lot.
confusing me for 2 days for this problem, but solove by your article.
greets.

Popular posts from this blog

Python中的self

习惯上,任何Python类方法的第一个参数(对当前实例d的引用)都叫做self。这个参数扮演着C++或Java中的保留字this的角色,但self在Python中并不是一个保留字,它只是一个命名习惯。虽然如此,也请除了self之外不要使用其它的名字,这是一个非常坚固的习惯。 出自:《Dive Into Python》

Google Notebook整合了Google 书签

FF上一直装有Google笔记本的插件,一直没有到一面上去看,今天无意点到。发现多了个叫“Unfiled”的记事本,记得自己并未建过这么个东西,进去一看才发现,其实就是我的Google书签: 并且右下角也多了“Labels”,且与我Google书签中的相同。 其实人家的右上角的“ New features! ”里说得很清楚: Integration with Google Bookmarks Notebook is now integrated with Google Bookmarks. Your bookmarks will show up as a special Unfiled notebook, making Google Notebook a single place to collect and organize interesting web pages. To publish and collaborate, just drag and drop bookmarks into notebooks.

sp_tables的@table_type参数

打算写个工具,直接从数据库按字段生成类,使用到了sp_tables,遇到了很奇怪的问题。 查MSDN可以知道:sp_tables的参数之一:@table_type varchar(100) 可选项有: TABLE 、 SYSTEMTABLE 、 VIEW 。 我写了如下代码: Databasedb = DatabaseFactory.CreateDatabase(); DbCommand com = new SqlCommand(); com.CommandText = "sp_tables"; com.CommandType = CommandType.StoredProcedure; com.Parameters.AddWithValue("@table_type", "TABLE"); IDataReader reader = db.ExecuteReader(com); 却拿不到任何东西。不加@talbe_type的话又返回了大量的系统VIEW。 查看sp_tables的源码,在关于@talbe_type的部分发现如下的东西: if (charindex('''TABLE''',@table_type) 0) 倒回去 仔细 看MSDN,参数的说明部分: [ , [ @table_type = ] "'type'" ] 比一般的多了2个",而且下面也有说明 Single quotation marks must enclose each table type, and double quotation marks must enclose the whole parameter. Table types must be uppercase. If SET QUOTED_IDENTIFIER is ON, each single quotation mark must be doubled and the whole parameter must be enclosed in single quotation marks. 太大意了。 修改代码: com.Parameters.AddWithValue(...