我将DataGridView控件绑定到List集合。因此,我可以编辑集合的元素。有什么方法可以使用此网格启用将元素删除和添加到集合的功能吗?
参考方案
通用List<T>
不完全支持对DataGridView
的绑定,如您所见,您可以编辑列表中的项目,但不能添加或删除。
您需要使用的是BindingList<T>
或BindingSource
。
BindingList<T>
允许您使用UI在网格中添加和删除行-当您将DataSource
更改为网格时,您将在网格的底部看到空白的新行。您仍然无法以编程方式添加或删除行。为此,您需要一个BindingSource
。
两者的示例如下(使用示例Users类,但此处的细节并不重要)。
public partial class Form1 : Form
{
private List<User> usersList;
private BindingSource source;
public Form1()
{
InitializeComponent();
usersList = new List<User>();
usersList.Add(new User { PhoneID = 1, Name = "Fred" });
usersList.Add(new User { PhoneID = 2, Name = "Tom" });
// You can construct your BindingList<User> from the List<User>
BindingList<User> users = new BindingList<User>(usersList);
// This line binds to the BindingList<User>
dataGridView1.DataSource = users;
// We now create the BindingSource
source = new BindingSource();
// And assign the List<User> as its DataSource
source.DataSource = usersList;
// And again, set the DataSource of the DataGridView
// Note that this is just example code, and the BindingList<User>
// DataSource setting is gone. You wouldn't do this in the real world
dataGridView1.DataSource = source;
dataGridView1.AllowUserToAddRows = true;
}
// This button click event handler shows how to add a new row, and
// get at the inserted object to change its values.
private void button1_Click(object sender, EventArgs e)
{
User user = (User)source.AddNew();
user.Name = "Mary Poppins";
}
}
将谓词<T>转换为Func <T,bool> - c#我有一个包含成员Predicate的类,希望在Linq表达式中使用该类:using System.Linq; class MyClass { public bool DoAllHaveSomeProperty() { return m_instrumentList.All(m_filterExpression); } private IEnumerable&…
Junit4和TestNG与Maven在一个项目中 - java要一起运行它们,几乎没有可用的选项,但是我选择为Junit和TestNG使用不同的配置文件。但是现在的问题是排除和包含测试用例。由于如果我们在Maven的主项目中添加testNG依赖项,它将跳过所有Junit,因此我决定将其放在单独的配置文件中。所以我使用pom.xml中的以下条目从默认(主要)配置文件中排除了TestNG测试:<plugin> …
通过Maven编译器插件不会发生有限的包含和排除 - java我正在使用3.6.0版的maven编译器插件,在此我们只想在特定文件夹中编译一个文件,而在该位置编译所有其他文件。例如:在文件夹应用程序中有14个文件,从那我只希望编译1个文件,但它编译了所有文件,如果我要排除,则它也不起作用。 <sourceDirectory>${basedir}/../src/java</sourceDirectory…
当我所有的都是T时,如何返回Interface <T>的实例? - java我有一个界面:public interface ILoginResult<T> { public T get(); } 我有一个LoginPage对象:public class LoginPage<T> { ... public ILoginResult<T> login(...) { ... } } 我也有一些登录页面对…
<T>如何在这里处理String和Integer - java我不明白T如何使用Integer和String。如此处显示功能中所示,T同时处理整数和字符串。该代码如何工作?class firstBase { <T> void display(T give_num, T give_String) { System.out.println("The given number is = " +…