我坚持以下问题:
我实现的datagridview必须总是有一个空行, 所以我使用BindingList作为DataSource
但是当以编程方式填充单元格时,不会添加任何行,
我可以通过在BindingList中添加一个项来添加一行,但是,如果我测试currentCell的位置,我就不能在BindingList中添加一个项:
例如,此代码为Ok,
public class MyObject: IMyObject
{
public BindingList<MyItem> MyCollectionToDisplay{ get; set; }
public void OneMoreLine()
{
MyItem myNewItem = new MyItem();
this.MyCollectionToDisplay.Add(myNewItem);
}
}
MydataGridView.DataSource = this.MyObject.MyCollectionToDisplay;
MydataGridView.CellLeave += MydataGridView_CellLeave;
private void MydataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
{
this.MyObject.OneMoreLine();
}
而且这个不是好的:
MydataGridView.DataSource = this.MyObject.MyCollectionToDisplay;
MydataGridView.CellLeave += MydataGridView_CellLeave;
private void MydataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
{
var rowNumberOfTheCell = MydataGridView.Rows[e.RowIndex].Index;
var totalOfRows = MydataGridView.Rows.Count;
if (rowNumberOfTheCell == totalOfRows - 1)
{
this.MyObject.OneMoreLine();
}
}
我有以下例外:
未处理的类型&#39; System.InvalidOperationException&#39;发生在System.Windows.Forms.dll中 附加信息:由于对象的当前状态,操作无效。
________________ EDIT ______________
好的,我明白了,
当单元格编辑DataSource时,我无法修改DataSource,
所以我用MouseDown事件替换CellLeave事件:
MydataGridView.DataSource = this.MyObject.MyCollectionToDisplay;
MydataGridView.CellLeave += MydataGridView_CellLeave;
private void MydataGridView_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
var rowIndex = this.MydataGridView.HitTest(e.X, e.Y).RowIndex;
var totalOfRows = this.MydataGridView.Rows.Count;
if (rowIndex == totalOfRows - 1)
{
this.MyObject.OneMoreLine();
}
}
}