c# - 如何允许在 DataGridView 上插入?

标签 c# winforms datagridview

我正在绑定(bind)一个 DataGridView来自List<T> .我已经设置上了设计师Enable adding .

如果列表为空,我将创建一个空列表以便显示标题,但它不会为我创建一个空行以便能够添加元素。为什么?我怎样才能让用户向这个列表中添加值?

一些代码

public IEnumerable<Value> ValueList
{
    get;
    set;
}

private void Form1_Load(object sender, EventArgs ev)
{
    if (ValueList == null)
    {
        ValueList = new List<Value>();
    }

    dataGrid.DataSource = ValueList;
}

最佳答案

首先, DataGridView.AllowUserToAddRows 必须是 true (这是因为您在设计器中设置了它)。

那个属性说

If the DataGridView is bound to data, the user is allowed to add rows if both this property and the data source's IBindingList.AllowNew property are set to true.

IBindingList.AllowNew (不可设置)还提到:

If IList.IsFixedSize or IList.IsReadOnly is true, this property returns false.

由于您绑定(bind)到 IEnumerable , 我相信 IsReadOnlyfalse .尝试将列表公开为 List<T>并绑定(bind)到 BindingList<T> .

public List<Value> ValueList
{
    get;
    set;
}

private void Form1_Load(object sender, EventArgs ev)
{
    if (ValueList == null)
    {
        ValueList = new List<Value>();
    }

    dataGrid.DataSource = new BindingList<Value>(ValueList);
}

关于c# - 如何允许在 DataGridView 上插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5575039/

相关文章:

c# - 将文件从一个文件夹移动到另一个 C#

c# - 在linq查询中设置匿名类型动态对象的所有属性

c# - 方法未找到 : 'System.Object Microsoft.EntityFrameworkCore.Infrastructure.IAnnotatable.get_Item(System.String)'

c# - WPF 以编程方式创建 TreeView 项模板/列

c# - C# 中 RectangleShape 的边框样式

c# - 如何在 DatagridView 列标题中添加图像?

c# - 单击按钮(而不是单击单元格)更改 dataGridView 单元格格式

c# Forms - MVC 框架?

winforms - 在 winforms 中引导依赖项(使用 StructureMap)

c# - 当 DataGridView 具有焦点时,如何让 "Accept"按钮触发?