开发者

C# Datagridview Edit Cell

I'm trying to put the cursor and focus in the las开发者_StackOverflow社区t row and a specific cell with the column named 'CheckNumber'. I thought I had it with this:

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

but it keeps coming up with this error:

Index -1 does not have a value.

Can someone please point me in the right direction!? This is driving me nuts.

Thank you!


Ok, I am going to preface this by saying that I cannot reproduce the issue you are having. However, you mentioned that the error actually occurs at dataGridView1.CurrentCell = cell; which should have ruled out the -1 index error.

Additionally, you said that the error you get is Index -1 does not have a value. That means that even though you have the right index, cell is still coming up as index -1. This means either the cell does not exist, or something else sketchy is happening. Since you sound like you've been at this for a while, I am assuming the cell actually exists.

Since the error doesn't seem to be in any of the 4 lines you've posted I would say take a look somewhere else, like when you first bind the source to the datagridview.

Update: I just found a few links relating to this. Since I don't know how you bound your datagridview, I don't really know if any of these apply, but if any do, let us know! In any case, it seems like it may apply to binding.

From: 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


Check the rowcount first, to make sure that you don't try to access a negative row number when there aren't any rows.

var c = dataGridView1.RowCount;

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜