【问题标题】:Set DataGridView rows after all are created to stop refresh全部创建后设置DataGridView行停止刷新
【发布时间】:2012-07-11 14:37:04
【问题描述】:

我正在向数据网格视图添加大量行,这个过程非常缓慢,因为它似乎在每次添加后都尝试重绘。

我在网上找不到一个示例,说明如何创建行列表(或数组,无论哪个有效),并在创建列表后一次将它们全部添加。不过,我需要这样做以阻止它在每次添加后重新绘制。

谁能提供一个简短的例子或给我一个好的文档?

【问题讨论】:

  • 是的,谢谢 :) 我知道我可以暂停控制绘图。我试图通过只填充一次控件来解决所有这些问题——比如当你构建一个长字符串然后设置文本框来保存它而不是在构建它时更新文本框 100 次。

标签: c# .net .net-3.5 datagridview


【解决方案1】:

您可能正在寻找 DataGridView.DataSource 属性。见http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource(v=vs.90).aspx

例如:

//Set up the DataGridView either via code behind or the designer
DataGridView dgView = new DataGridView();

//You should turn off auto generation of columns unless you want all columns of
//your bound objects to generate columns in the grid
dgView.AutoGenerateColumns = false; 

//Either in the code behind or via the designer you will need to set up the data
//binding for the columns using the DataGridViewColumn.DataPropertyName property.
DataGridViewColumn column = new DataGridViewColumn();
column.DataPropertyName = "PropertyName"; //Where you are binding Foo.PropertyName
dgView.Columns.Add(column);

//You can bind a List<Foo> as well, but if you later add new Foos to the list 
//reference they won't be updated in the grid.  If you use a binding list, they 
//will be.
BindingList<Foo> listOfFoos = Repository.GetFoos();

dgView.DataSource = listOfFoos;

此时要绑定的一个方便的事件是 DataGridView.DataBindingComplete,它在数据源绑定后触发。

【讨论】:

  • 感谢您的详细描述:)
【解决方案2】:

这里有几个想法:

1) 将列表绑定到 DataGridView。当您设置DataGridView.DataSource = MyList 时,它会立即更新整个网格,而无需进行所有逐行操作。您可以将项目添加到 MyList,然后重新绑定到 DataGridView。 (我更喜欢使用动态更新 DataGridView 网格的 BindingList。)

2) 如果数据绑定不是一个选项,我过去所做的是在更新之前为每一列设置AutoSizeMode = NotSet,然后将其设置回之前的状态。真正减慢绘图速度的是AutoSizeMode

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多