Click here to Skip to main content
15,886,689 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:

C#
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();
            }


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!
Posted

1 solution

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 throws ArgumentOutOfRangeException.

Fix this trivial bug first, and then see if you have other problems. :-)

—SA
 
Share this answer
 
Comments
joshrduncan2012 29-Jan-13 16:32pm    
That fix didn't help in solving clicking on a column that will not through an ArgumentOutOfRangeException. No changes in output.
joshrduncan2012 29-Jan-13 16:45pm    
It looks like if I check for both, then both of them error out.
joshrduncan2012 29-Jan-13 16:53pm    
I found the issue. I had to enclose this plus a lot of other stuff inside of a try/catch and now I can select rows/columns/cells no problem. :)
Sergey Alexandrovich Kryukov 29-Jan-13 16:58pm    
OK, great, but I correctly identified the bug. Will you accept the answer formally (green button)? — thanks.
—SA
joshrduncan2012 29-Jan-13 17:00pm    
The answer really didn't solve what I was looking for, but since you asked nicely, I did accept anyway. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900