I was trying to get the row count of a DataGridView [ dataGridView1.Rows.Count ]. I found out that the row count is still 0 when though the UI shows multiple rows added already in the DataGridView. I figured out that this might be a threading thinggy so I used the following code to retrieve the row count :
public void OnTagsReported( ... )
{
...
for( var i = GetDataGridViewRowCount( dgvScanResult ) - 1; i >= 0; i-- )
{
var row = dgvScan.Rows[ i ];
...
}
...
}
protected int GetDataGridViewRowCount( DataGridView gridView )
{
try
{
if( ! InvokeRequired )
{
return gridView.Rows.Count;
}
var count = 0;
var action = new Action<DataGridView>( delegate( DataGridView c )
{ count = c.Rows.Count; } );
gridView.Invoke( action, gridView );
return count;
}
catch( ObjectDisposedException ) {}
catch( InvalidOperationException ) {}
}
I get the row count but was wondering if this is the correct way. May I know how would ya’ll do it?
Thank you all for your kind attention and opinion.
Why is your OnTagsReported method in another thread? Anyway, two comments.
First: Yes you can do it like that, but in GetDataGridViewRowCount is an error. You should call InvokeRequired also on the gridView because you are using gridview.Invoke later on.
Second: Better call your OnTagsReported method in the correct thread. Then you don’t need the GetDataGridViewRowCount method.