2011-04-03 157 views
1

我试图把光标和焦点放在最后一行和一列名为'CheckNumber'的特定单元格。我想我这个了吧:C#Datagridview编辑单元格

var c = dataGridView1.RowCount; 
    DataGridViewCell cell = dataGridView1.Rows[c-1].Cells[0]; 
    dataGridView1.CurrentCell = cell; 
    dataGridView1.BeginEdit(true); 

但它一直想出这个错误:

指数-1不具有价值。

有人可以请指点我正确的方向!?这让我疯狂。

谢谢!

+0

此代码运行时有什么行数?是0吗? – David 2011-04-03 21:02:10

+0

RowCount = 1我在'dataGridView1.CurrentCell = cell; 'line – ErocM 2011-04-03 21:08:23

回答

2

好吧,我要说,我不能再现你遇到的问题。但是,您提到错误实际发生在dataGridView1.CurrentCell = cell;,应该排除-1索引错误。

此外,你说你得到的错误是Index -1 does not have a value.这意味着,即使你有正确的索引,cell仍然是索引-1。这意味着单元格不存在或者其他粗略的事情正在发生。既然你听起来像你已经有一段时间了,我认为这个单元格实际上存在。

由于错误似乎没有在您发布的4行中的任何一行中,我会说看看别的地方,比如当您第一次将源绑定到datagridview时。

更新:我只是找到了几个与此相关的链接。由于我不知道你是如何绑定datagridview的,所以我不知道它们是否适用,但如果有的话,请告诉我们!无论如何,它似乎可能适用于绑定。

来源:SO Question 1

If you initially bind an empty collection that does not inform the DGV of changes (e.g. a Collection does not, but a BindingList does), the initial current row offset will be correctly set to -1, (Because it is empty.)

When you subsequently add objects to your data bound collection they will still display correctly on the grid, but the CurrencyManager will not be informed of any changes, and the current row offset will remain stubbornly at -1.

So, when you try to edit a row, the CurrencyManager thinks you are trying to edit a row at offset -1, and the exception is thrown.

To combat this, you need to rebind before interacting with a row, or initially bind a Collection etc when it contains one or more items.

SO Question 2

.NET Monster Question

+0

这就是我一直在寻找的!非常感谢你! – ErocM 2011-04-09 14:50:53

0

首先检查rowcount,以确保在没有任何行时不尝试访问否定行号。

var c = dataGridView1.RowCount; 

if(c>0){ 
    DataGridViewCell cell = dataGridView1.Rows[c-1].Cells[0]; 
    dataGridView1.CurrentCell = cell; 
    dataGridView1.BeginEdit(true); 
} 
+0

My RowCount = 1,我添加了一个包装器,它不会停止消息。我必须将代码混淆在某处... – ErocM 2011-04-04 15:16:21

相关问题