We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,939 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

get the row number of datagridview

I have a datagridview and a status strip on my form. When I click a row or cell, the label from the status strip should change according to it's row number. My datagridview is being generated at run time by a dataset.

3
Contributors
6
Replies
3 Hours
Discussion Span
2 Years Ago
Last Updated
7
Views
Question
Answered
AngelicOne
Posting Whiz
362 posts since Jul 2010
Reputation Points: 14
Solved Threads: 2
Skill Endorsements: 0

Many Click events of the DataGrridView show a DataGridViewCellEventArgs

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // e.RowIndex and e.ColumnIndex
        }

This class gives you access to the row and column.

ddanbe
Industrious Poster
4,287 posts since Oct 2008
Reputation Points: 2,121
Solved Threads: 722
Skill Endorsements: 26

I will only add to ddanbe` post:
If you are not in some dgv`s event handler you get the row number like:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int rowIndex1 = e.RowIndex;
            int rowIndex2 = GetRowIndex();
        }

        private int GetRowIndex()
        {
            int rowIndex = this.dataGridView1.CurrentCell.RowIndex;
            return rowIndex;
        }

Mitja

Mitja Bonca
Posting Maven
2,561 posts since May 2009
Reputation Points: 642
Solved Threads: 486
Skill Endorsements: 13

It begins with 0 for the first row, so does that mean I just need to add 1?

AngelicOne
Posting Whiz
362 posts since Jul 2010
Reputation Points: 14
Solved Threads: 2
Skill Endorsements: 0

Depends on what your intentions are, as long as you know what you are doing, please add 1. No problem.

ddanbe
Industrious Poster
4,287 posts since Oct 2008
Reputation Points: 2,121
Solved Threads: 722
Skill Endorsements: 26

There's an error if I click an empty datagridview. I suppose I need to set a condition for this? Like if datagridview is not null?

I need to indicate the row is 0, so I think an if else condition is necessary, don't you think? But using condition just to tell the row is 0? Isn't the code supposed to do that?

AngelicOne
Posting Whiz
362 posts since Jul 2010
Reputation Points: 14
Solved Threads: 2
Skill Endorsements: 0

Yes you do:

if(dataGridView1.Rows.Count > 0)
{
   //your code
}
Mitja Bonca
Posting Maven
2,561 posts since May 2009
Reputation Points: 642
Solved Threads: 486
Skill Endorsements: 13
Question Answered as of 2 Years Ago by ddanbe and Mitja Bonca

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0893 seconds using 2.65MB