首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DataGridViewColumn.DataPropertyName属性

DataGridViewColumn.DataPropertyName属性
EN

Stack Overflow用户
提问于 2010-02-08 19:27:02
回答 5查看 11.5K关注 0票数 7

我有一个DataGridView控件,我想用数据填充它。

我使用DataSource属性

代码语言:javascript
复制
// dgvDealAsset is DataGridView
        private void DealAssetListControl_Load(object sender, EventArgs e)
        {
            dgvDealAssets.AutoGenerateColumns = false;
            dgvDealAssets.DataSource = DealAssetList.Instance.Values.ToList();
}

现在是第一个问题。我的集合的类并不只包含我可以使用DataPropertyName映射到列的简单类型。这是集合中包含的类。

代码语言:javascript
复制
class MyClass
{
  public String Name;
  MyOtherClass otherclass;
}

class MyOtherClass
{
 public String Name;
}

现在,我正在将MyClass的属性绑定到列

代码语言:javascript
复制
col1.DataPropertyName = "Name"  // Ok 
col2.DataPropertyName = "otherclass" // Not OK - I will have empty cell

问题是我想要显示otherclass.Name字段。但如果我试着写

代码语言:javascript
复制
col2.DataPropertyName = "otherclass.Name" 

我得到了空的单元格。

我试着手动设置列

代码语言:javascript
复制
private void DealAssetListControl_Load(object sender, EventArgs e)
{
    dgvDealAssets.AutoGenerateColumns = false;
    dgvDealAssets.DataSource = DealAssetList.Instance.Values.ToList();

// iterate through rows and set the column manually
        foreach (DataGridViewRow row in dgvDealAssets.Rows)
        {
            row.Cells["Column2"].Value = ((DealAsset)row.DataBoundItem).otherclass.Name;
        }

但是这个foreach循环大约需要几分钟才能完成(2k个元素)。如何解决这个问题?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-02-09 05:10:53

DataGridView不支持对子属性进行数据绑定。有关更多信息,请查看this post

我喜欢使用CellFormatting事件的解决方案。

票数 3
EN

Stack Overflow用户

发布于 2010-02-08 19:32:35

问题nr.1:

尝试执行以下操作:

  1. extend MyOtherClass from Object (可能不需要此步骤)并覆盖或创建方法ToString()。

这应该就行了。

票数 3
EN

Stack Overflow用户

发布于 2015-10-07 18:07:26

如果你想使用很多这样的子元素:

代码语言:javascript
复制
class MyClass
{
   public int Id;
   public MyOtherClass OtherClass;
}

class MyOtherClass
{
   public string Name;
   public int Number;
}

怎么样

for 在某些事件中为每个单元格设置值(最好是另一个),在设置数据源后手动设置,例如:

代码语言:javascript
复制
private void dgv_CellFormatting( object sender, DataGridViewCellFormattingEventArgs e )
{
   MyClass data = dgv.Rows[ e.RowIndex ].DataBoundItem as MyClass;

   dgv.Rows[ e.RowIndex ].Cells[ "colName" ].Value = data.OtherClass.Name;
   dgv.Rows[ e.RowIndex ].Cells[ "colNumber" ].Value = data.OtherClass.Number;
}

第二个解决方案如何从数据创建一个DataTable,然后绑定它?

我将非常感谢您的任何意见;-)

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2221207

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档