Click here to Skip to main content
12,946,164 members (60,349 online)
Rate this:
Please Sign up or sign in to vote.
See more:

I have this little problem.

I have datagridview and on CellClick event I have this code.
dg.Rows[e.RowIndex].Selected = true;

I use this event to select row on click on any cell, but now here comes the problem when I click on the Header of column to sort the column, I cant.

I get this error.
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Anyone? Thanks in advance.
Posted 9-Nov-12 1:49am
Updated 9-Nov-12 5:14am
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

u can check for Header row in CellClick event and dont process for header row. Header row has index -1. so try this:
private void gv_CellClick(object sender, DataGridViewCellEventArgs e)
    if (e.RowIndex != -1)
        //Your code
shonezi 9-Nov-12 8:06am
thank you, works great
Gautam Raithatha 9-Nov-12 8:44am
Marcus Kramer 9-Nov-12 11:56am
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

I changed code to this

dg.CurrentRow.Selected = true;

now it works, but still its on CellClick event, maybe something different has to be done if it should not be on CellClick event
Rate this: bad
Please Sign up or sign in to vote.

Solution 1


Cell click event is not good, you try to use Gridview RowCommand event is to be better

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

    Print Answers RSS
Top Experts
Last 24hrsThis month
OriginalGriff 4,899
CHill60 3,205
Maciej Los 2,453
Jochen Arndt 1,935
ppolymorphe 1,795

Advertise | Privacy | Mobile
Web02 | 2.8.170518.1 | Last Updated 9 Nov 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100