I'm trying to access column name of the selected row in DataGridView control in windows form, but I'm getting ArgumenOutOfRange exception of the following code:
MessageBox.Show(dataGridView1.SelectedColumns[dataGridView1.CurrentCell.ColumnInd开发者_如何学Cex].ToString());
Producing:
ArgumentOutOfRangeException was unhandled
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Could anyone please tell me how can I overcome from this error?
SelectedColumns
is a list that only contains the selected columns (yeah, that's how it works). So this list size is different from the size of the Columns
property list (which is what you want, obviously).
MessageBox.Show(dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].ToString());
If I am not wrong, then probably you should be getting column value from a Columns
collection and not from SelectedColumns
collection.
dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex]
The DataGridView.SelectedColumns collection is a separate collection from the DataGridView.Columns and can have a different set (a subset) of the columns.
For example if you have a 5 column view, and the third and the fourth are selected, then
DataGridView.SelectedColumns.Count == 2
DataGridView.Columns.Count == 5
and of you are using the fourth column (index of 3) your code becomes
DataGridView.SelectedColumns[3]
which blows up (rightly) with a IndexOutOfBounds.
To sum it up, in your case, you should be using the Columns property, and not the SelectedColumns.
The ColumnIndex
property can return -1 (from the documentation):
The index of the column that contains the cell; -1 if the cell is not contained within a column.
Could this be the case for you?
精彩评论