在数据绑定DataGridView中添加条目 [英] Add entry into databound DataGridView
本文介绍了在数据绑定DataGridView中添加条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨伙计们,
用户应该可以编辑这些可爱的小型演示对象列表:
Hi folks,
user shall be able to edit a list of these cute little demo objects:
class Foo
{
public int FirstCol { get; set; }
public int SecondCol { get; set; }
public Foo(int first, int second)
{
FirstCol = first;
SecondCol = second;
}
}
public void WindowsFormsMethod()
{
BindingList<Foo> list = new BindingList<Foo>();
list.Add(new Foo(1, 2));
list.Add(new Foo(2, 3));
list.Add(new Foo(42, 32));
dgvEditor.DataSource = bla;
// dgvEditor.AllowUserToAddRows is already true
}
并且通过编辑,我的意思是他可以改变值,它可以工作,_和_添加新行,但不是。如何让用户添加行?
And by "edit", I mean he can change values, which works, _and_ add new rows, which doesn't. How can I enable user to add rows?
推荐答案
As a result of googling a lot I've come to a decision that actually there is no way to add new row to a datagridview which has a binding source.However I am not sure at all.But According to your need I am giving you a solution I think it works for you fine.Please check it.Thanks
public Form1()
{
InitializeComponent();
BindingList<foo> list = new BindingList<foo>();
list.Add(new Foo(1, 2));
list.Add(new Foo(2, 3));
list.Add(new Foo(42, 32));
list.Add(new Foo(0, 0));
dgvEditor.Columns.Add("FirstCol", "First Column");
dgvEditor.Columns.Add("SecondCol", "Second Column");
int count=0;
foreach (Foo f in list)
{
dgvEditor.Rows.Add();
dgvEditor[0, count].Value = f.FirstCol;
dgvEditor[1, count].Value = f.FirstCol;
count++;
}
}
解决方案是添加无参数的Foo构造函数。
The solution is to add a parameterless Foo constructor.
class Foo
{
public int FirstCol { get; set; }
public int SecondCol { get; set; }
// This c'tor is needed for the user
// to add entries from within
// a databound DataGridView.
public Foo()
{ }
public Foo(int first, int second)
{
FirstCol = first;
SecondCol = second;
}
}
public void WindowsFormsMethod()
{
BindingList<Foo> list = new BindingList<Foo>();
list.Add(new Foo(1, 2));
list.Add(new Foo(2, 3));
list.Add(new Foo(42, 32));
dgvEditor.DataSource = list;
// dgvEditor.AllowUserToAddRows is already true
}
我试图避免这种情况,因为参数化的c'tor检查了它作为参数得到的值。将不得不以另一种方式执行这些。
Which I tried to avoid because the parameterized c'tor did some checking of the values it got as parameters. Will have to perform those in another way.
这篇关于在数据绑定DataGridView中添加条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文