简体   繁体   English

在DataGridView(C#)中将类实例添加为新行

[英]Adding Class instance as a new Row in DataGridView (c#)


I have a class say 我有一堂课

[Serializable]
    public class Answer
    {
        [DisplayName("ID")]
        public string ID { get; set; }
        [DisplayName("Value")]
        public string Value { get; set; }
    }

and I have a datagridview with bounded columns to the above class. 而且我有一个datagridview带有上面的类的有界列。

instances of this class Answer are created dynamically as and when required. 此类的实例会在需要时动态创建。 How do I update datagridview when each and every instance of class is created. 创建类的每个实例时,如何更新datagridview。

is it possible to do something of this sort. 是否有可能做这种事情。

dataGridView.Rows.Add(classInstance);

Thanks in Advance, 提前致谢,
Amit 阿米特

Yes, but not the way you do it. 是的,但不是您的方式。

You need to use databinding. 您需要使用数据绑定。

Something like the following should work: 类似于以下内容的东西应该起作用:

var ds = new BindingList<Answer>();
dgv.DataSource = ds;

Now when you do: 现在,当您执行以下操作时:

ds.Add( new Answer { ... });

it will be added (as you wanted). 它将被添加(根据需要)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM