检查是否在datagridview中选择了行/列/单元格 [英] Checking for whether rows/columns/cells are selected in datagridview
问题描述
大家好!
我在检查数据网格视图中是否选择了单元格/列/行时遇到问题。
这是我的代码:
Hi everyone!
I am having an issue with checking for whether or not cells/columns/rows are selected in a datagridview.
Here is my code:
bool isRowSelected = dataGridView1.Rows[e.RowIndex - 1].Selected;
bool isColumnSelected = dataGridView1.Columns[e.ColumnIndex].Selected;
if (((dataGridView1.CurrentCell.ColumnIndex == 0) || (dataGridView1.CurrentCell.ColumnIndex == 1) || (dataGridView1.CurrentCell.ColumnIndex == 2)
|| (dataGridView1.CurrentCell.ColumnIndex == 3) || (dataGridView1.CurrentCell.ColumnIndex == 4)) && (!isRowSelected) || (!isColumnSelected))
{
this.comboBox1.Location = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Location;
comboBox1.Width = 100;
this.comboBox1.SelectedValue = this.dataGridView1.CurrentCell.Value;
this.comboBox1.Show();
}
预期输出:
单元格选择 - 组合框应该位于选定的单元格
行选中 - 突出显示该行而不显示任何其他内容
选择列 - 突出显示该列(或)按该列排序
实际输出:
单元格和行选择 - 相同
列选择 - 这是指向此行的错误。
bool isRowSelected = dataGridView1.Rows [e.RowIndex - 1] .Selected;
原因:索引超出范围。必须是非负数且小于集合的大小。 (ArgumentOutOfRangeException)
我想避免在选择行或列时出现组合框,只选择单元格选择。这是我的意图。
谢谢大家!
Expected Output:
Cell selected - combobox is supposed to be on top of the selected cell
Row selected - highlight that row and nothing else
Column selected - highlight that column (or) sort by that column
Actual Output:
Cell and Row selection - same
Column selection - this is erroring out pointing to this line.
bool isRowSelected = dataGridView1.Rows[e.RowIndex - 1].Selected;
For the reason of: Index was out of range. Must be non-negative and less than the size of the collection. (ArgumentOutOfRangeException)
I want to avoid having the combobox appear when a row or column is selected, just cell selection only. That is my intent.
Thanks everyone!
推荐答案
我能看到的第一个错误是:e.RowIndex
可以是0,在这种情况下,e.RowIndex - 1
将为-1,这当然是超出范围,使用此索引值进行索引会抛出ArgumentOutOfRangeException
。
先修复此琐碎错误,然后再看如果你有其他问题。 :-)
-SA
The first bug I can see is:e.RowIndex
can be 0, in this case,e.RowIndex − 1
will be −1, which is of course out of range, indexing with this index value throwsArgumentOutOfRangeException
.
Fix this trivial bug first, and then see if you have other problems. :-)
—SA
这篇关于检查是否在datagridview中选择了行/列/单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!