我正在绑定(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
, 我相信 IsReadOnly
是false
.尝试将列表公开为 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/